TCP-based Java Socket programming is implemented. The function is simple: the client outputs a "connect" to the server ", the server receives and sends a message "Hello" to the console. The client receives and outputs the message.
1. Server Side
Java code
- Package e.net. socket;
- Import java. io. DataInputStream;
- Import java. io. DataOutputStream;
- Import java. io. IOException;
- Import java. io. InputStream;
- Import java. io. OutputStream;
- Import java.net. ServerSocket;
- Import java.net. Socket;
- Public class TCPServer {
- Public static void main (String [] args ){
- Try {
- ServerSocket serverSocket = new ServerSocket (8888 );
- Socket socket = serverSocket. accept ();
- // Read client data
- InputStream info = socket. getInputStream ();
- DataInputStream dis = new DataInputStream (info );
- System. out. println (dis. readUTF ());
- // Output data to the client
- OutputStream OS = socket. getOutputStream ();
- DataOutputStream dos = new DataOutputStream (OS );
- Dos. writeUTF ("Hello! ");
- Dos. flush ();
- } Catch (IOException e ){
- E. printStackTrace ();
- }
- }
- }
2. Client:
Java code
- Package e.net. socket;
- Import java. io. DataInputStream;
- Import java. io. DataOutputStream;
- Import java. io. IOException;
- Import java. io. InputStream;
- Import java. io. OutputStream;
- Import java.net. Socket;
- Import java.net. UnknownHostException;
- Public class TCPClient {
- Public static void main (String [] args ){
- Try {
- Socket socket = new Socket ("192.168.1.123", 8888 );
- // Send data to the server
- OutputStream OS = socket. getOutputStream ();
- DataOutputStream bos = new DataOutputStream (OS );
- Bos. writeUTF ("Connect ");
- Bos. flush ();
- // Receives server data
- InputStream is = socket. getInputStream ();
- DataInputStream dis = new DataInputStream (is );
- System. out. println (dis. readUTF ());
- } Catch (UnknownHostException e ){
- E. printStackTrace ();
- } Catch (IOException e ){
- E. printStackTrace ();
- }
- }
- }