Java Network Programming (4)--TCP

Source: Internet
Author: User

TCP relative to UDP is a connection-oriented protocol, the most important feature to establish a connection to communicate, the client with a socket needs to point the address and port, the service end with Servesocket, just to listen to a port, because it is a connection-oriented, so the server must first run up, Then the client can find our server through the address and port, and after establishing the connection, we can communicate!

A small example of a client communication that implements the simplest service-side first

Client:

 Packagecom.seven.tcp;ImportJava.io.OutputStream;ImportJava.net.Socket; Public classTcpClient { Public Static voidMain (string[] args)throwsException {Socket Socket=NewSocket ("127.0.0.1", 10001); OutputStream out=Socket.getoutputstream (); Out.write ("Hello TCP". GetBytes ());    Socket.close (); } }

Service side:

 Packagecom.seven.tcp;ImportJava.io.InputStream;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classTCPServer { Public Static voidMain (string[] args)throwsException {serversocket serversocket=NewServerSocket (10001); //Get Client SocketSocket socket =serversocket.accept (); InputStream in=Socket.getinputstream (); byte[] B =New byte[1024];  while(true){            intLen =In.read (b); if(len =-1) Break; System.out.println (socket.getinetaddress ()+ "---->" +NewString (b,0, Len));     } socket.close (); }}

In this way, the client service side of the communication between, in fact, mainly through the socket object implementation, the client socket outputstream corresponding to the server socket InputStream, And the service side of the OutputStream on the corresponding client InputStream, through the two streams to achieve communication, including text, pictures, files, and so on, just the file into a byte stream can be transmitted through TCP!

Java Network Programming (4)--TCP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.