Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use TCP Socket

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "how to use TCP Socket". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn how to use TCP Socket.

Java provides two classes for the TCP protocol, which are used in client-side programming and server-side programming. Before the application starts to communicate, it needs to create a connection initiated by the client program, while the server-side program needs to listen to the specific port number of the host all the time, waiting for the client to connect. In the client side, we only need to use the Socket instance, while the server side processes both the ServerSocket instance and the Socket instance; and both use OutputStream and InpuStream to send and receive data.

The way to learn a knowledge * is to use it. Through the previous notes, we already know how to get the address information of the host. Now we use a simple program to learn the Socket programming of the transport layer using the TCP protocol.

TCP server side

In Socket programming, the server side is much more complex than the client side. The job of the server is to establish a communication terminal and passively wait for the connection of the client. The following example of a server-side program is used to listen to the port number entered from the console and send back the message sent by the client.

Import java.net.*; import java.text.MessageFormat; import java.io.*; public class TCPEchoServer {private static final int BUFSIZE = 32 / * @ param args * / public static void main (String [] args) throws IOException {/ / TODO Auto-generated method stub / / obtain the port number if (args.length! = 1) throw new IllegalArgumentException ("Parameter (s):") that you want to listen to from the console / / get port number int servPort = Integer.parseInt (args [0]); / / instantiate a ServerSocket object instance ServerSocket servSocket = new ServerSocket (servPort); System.out.println ("start snooping, port number: {0}", args [0])) / / Total bytes of initial received data int recvMsgSize; / / buffer byte of received data [] receiveBuf = new byte [BUFSIZE] / / iterate through the loop, listen for port numbers, process new connection requests while (true) {/ / blocking wait, create a new connection instance Socket clntSocket = servSocket.accept () every time you receive a request; / / get the SocketAddress SocketAddress clientAddress = clntSocket.getRemoteSocketAddress () of the connected client / / printout connection client address information System.out.println ("Handling client at" + clientAddress); / / object receiving data from client InputStream in = clntSocket.getInputStream (); / / object sending data to client OutputStream out = clntSocket.getOutputStream () / / read the data sent by the client, and then send it to the client while ((recvMsgSize = in.read (receiveBuf))! =-1) {out.write (receiveBuf, 0, recvMsgSize) } / / when the client closes the connection, close the connection System.out.println ("client closes the connection"); clntSocket.close ();}

TCP client

In Socket programming, the client first needs to send to the server, and then passively wait for the response from the server. In the following example: we send a message to the server, wait for the message from the server, and print it.

Import java.io.*; import java.net.Socket; import java.net.SocketException; public class TCPEchoClient {/ * * @ param args * @ throws IOException * / public static void main (String [] args) throws IOException {/ / TODO Auto-generated method stub / / determine whether the parameters accepted from the console are correct if ((args.length)

< 2) || (args.length >

3) throw new IllegalArgumentException ("Parameter (s): []]"); / / get the server address String server = args [0]; / / get the information to be sent byte [] data = args [1] .getBytes () / / if there are three parameters, then get the port number to send the message. The default port number is 8099 int servPort = (args.length = = 3)? Integer.parseInt (args [2]): 8099; / / instantiate a Socket instance based on server address and port number Socket socket = new Socket (server, servPort); System.out.println ("Connected to server...sending echo string"); / / returns the input stream of this socket, that is, the data object InputStream in = socket.getInputStream () received from the server / / returns the output stream of this socket, that is, the data object sent to the server OutputStream out = socket.getOutputStream (); / / sends the data received from the console out.write (data) to the server; / / the counter that receives the data, and writes the initial offset of the data int totalBytesRcvd = 0 / / initialize the total number of bytes of received data int bytesRcvd; while (totalBytesRcvd

< data.length) { // 服务器关闭连接,则返回 -1,read方法返回接收数据的总字节数 if ((bytesRcvd = in.read(data, totalBytesRcvd, data.length - totalBytesRcvd)) == -1) throw new SocketException("与服务器的连接已关闭"); totalBytesRcvd += bytesRcvd; } // 打印服务器发送来的数据 System.out.println("Received:" + new String(data)); // 关闭连接 socket.close(); } } 首先运行服务器端,监听8099端口:

Then run the client program and send a message to the server:

Looking at our server-side console again, we can see the address information of the previous client connection:

Thank you for your reading, the above is the content of "how to use TCP Socket", after the study of this article, I believe you have a deeper understanding of how to use TCP Socket, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report