TCP communication programming-JAVA Implementation
Client programming steps:
- Establish a network connection
- Exchange data
- Disable network connection
Server programming steps:
- Listening port
- Get connection
- Exchange data
- Close connection
This article mainly describes the following types:
The inetaddress class indicates an IP address, and includes the operation methods related to the IP address and domain name in the class.
The serversocket class is used to establish a socket for the server. Its main function is to wait for "requests" from the network. It can wait for a socket that is strongly connected through a specified port.
After a socket object is created for a scoket client, it attempts to connect to the specified IP address and port. The server creates a new socket to establish a connection with the client socket.
The following is the source code for communication between the client and the server in C/S mode.
Import Java. io. datainputstream; import Java. io. dataoutputstream; import Java. io. ioexception; import Java. io. inputstream; import Java. io. outputstream; import java.net. inetaddress; import java.net. serversocket; import java.net. socket; public class scoketserver {/*** @ Param ARGs * @ throws ioexception */public static void main (string [] ARGs) throws ioexception {// todo auto-generated method stubserversocket s Erversocket = NULL; socket clientsocket = NULL; datainputstream in = NULL; dataoutputstream out = NULL; system. Out. println ("waiting for connection .... "); Serversocket = new serversocket (4332); clientsocket = serversocket. accept (); In = new datainputstream (clientsocket. getinputstream (); out = new dataoutputstream (clientsocket. getoutputstream (); inetaddress clientip = clientsocket. getinetaddress (); system. out. println (clientip); system. out. println (clientsocket. getport (); out. writeutf ("Welcome ........ "); string line = in. readline (); While (line! = "Quit") {system. Out. println (line); In. Readline ();}}}
import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.net.Socket;import java.net.UnknownHostException;
Public class clientsocket {/*** @ Param ARGs * @ throws ioexception * @ throws unknownhostexception */public static void main (string [] ARGs
) Throws unknownhostexception, ioexception {// todo auto-generated method stubsocket clientsocket; datainputstream in = NULL; dataoutputstream out = NULL; clientsocket = new socket ("127.0.0.1", 4332 ); in = new datainputstream (clientsocket. getinputstream (); out = new dataoutputstream (clientsocket. getoutputstream (); out. writeutf ("I Am a client ...... "); String STR = NULL; while (true) {STR = in. Readline (); system. Out. println (STR );}}}