An example of communication between a Java Socket server and a client

Source: Internet
Author: User

An example of HelloWord-level Java Socket communication. Communication Process:
Start the Server first and enter an endless loop so that you can monitor whether a port has connection requests. Then run the Client, and the Client sends a connection request. After listening to this request, the server sends a message to the Client to receive the message, establishes the connection, and starts a thread to process the request, then listen to other requests in an endless loop. After the client inputs a string, press enter to send data to the server. The server reads the data and replies to the client. After the request is processed, the starting thread disappears. If the client receives data outside of "OK", it will send a connection request again and send data. The server will start a thread for the connection again to respond... The client exits when the returned data received by the client is "OK.
Server Source Code:
[Java]
Package com. defonds. socket. begin;
 
Import java. io. BufferedReader;
Import java. io. DataInputStream;
Import java. io. DataOutputStream;
Import java. io. InputStreamReader;
Import java.net. ServerSocket;
Import java.net. Socket;
 
Public class Server {
Public static final int PORT = 12345; // The listening PORT number

Public static void main (String [] args ){
System. out. println ("server startup... \ n ");
Server server = new Server ();
Server. init ();
}

Public void init (){
Try {
ServerSocket serverSocket = new ServerSocket (PORT );
While (true ){
// Once there is a blockage, it indicates that the server is connected to the client.
Socket client = serverSocket. accept ();
// Process the connection
New HandlerThread (client );
}
} Catch (Exception e ){
System. out. println ("server exception:" + e. getMessage ());
}
}

Private class HandlerThread implements Runnable {
Private Socket socket;
Public HandlerThread (Socket client ){
Socket = client;
New Thread (this). start ();
}

Public void run (){
Try {
// Read client data
DataInputStream input = new DataInputStream (socket. getInputStream ());
String clientInputStr = input. readUTF (); // note that this parameter corresponds to the write method of the client output stream; otherwise, an EOFException is thrown.
// Process client data
System. out. println ("content sent from the client:" + clientInputStr );

// Reply to the client
DataOutputStream out = new DataOutputStream (socket. getOutputStream ());
System. out. print ("enter \ t ");
// Send a line of keyboard input
String s = new BufferedReader (new InputStreamReader (System. in). readLine ();
Out. writeUTF (s );

Out. close ();
Input. close ();
} Catch (Exception e ){
System. out. println ("Server run exception:" + e. getMessage ());
} Finally {
If (socket! = Null ){
Try {
Socket. close ();
} Catch (Exception e ){
Socket = null;
System. out. println ("server finally exception:" + e. getMessage ());
}
}
}
}
}
}
Client source code:
[Java]
Package com. defonds. socket. begin;
 
Import java. io. BufferedReader;
Import java. io. DataInputStream;
Import java. io. DataOutputStream;
Import java. io. IOException;
Import java. io. InputStreamReader;
Import java.net. Socket;
 
Public class Client {
Public static final String IP_ADDR = "localhost"; // server address
Public static final int PORT = 12345; // server PORT number

Public static void main (String [] args ){
System. out. println ("Start the client ...");
System. out. println ("when the received server character is \" OK \ ", the client terminates \ n ");
While (true ){
Socket socket = null;
Try {
// Create a stream socket and connect it to the specified port number on the specified host
Socket = new Socket (IP_ADDR, PORT );

// Read server data
DataInputStream input = new DataInputStream (socket. getInputStream ());
// Send data to the server
DataOutputStream out = new DataOutputStream (socket. getOutputStream ());
System. out. print ("enter \ t ");
String str = new BufferedReader (new InputStreamReader (System. in). readLine ();
Out. writeUTF (str );

String ret = input. readUTF ();
System. out. println ("the server returns:" + ret );
// Disconnect if "OK" is received
If ("OK". equals (ret )){
System. out. println ("the client will close the connection ");
Thread. sleep (500 );
Break;
}

Out. close ();
Input. close ();
} Catch (Exception e ){
System. out. println ("client exception:" + e. getMessage ());
} Finally {
If (socket! = Null ){
Try {
Socket. close ();
} Catch (IOException e ){
Socket = null;
System. out. println ("client finally exception:" + e. getMessage ());
}
}
}
}
}
}

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.