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