Java Socket Communication instance

Source: Internet
Author: User

I have been working on Java web and have hardly done anything in the CS direction. I recently learned to work in Beijing and come to my place. Speaking of the written examination experience, this is probably the case with such a procedural question;
C ++ programming is used to implement a simple communication instance, requiring the server to accept messages sent from the client in real time. Although I have never done anything in this area, I also know that Java Socket is required to implement it (Frankly speaking, C ++ won't ). After work, I spent two hours writing an instance that basically met the requirements. Some problems have also been encountered, posted and learned together.
Paste the code first. Server:
[Java]
Package qy. server;
 
Import java. io. DataInputStream;
Import java. io. DataOutputStream;
Import java. io. IOException;
Import java.net. ServerSocket;
Import java.net. Socket;
Import java. util. concurrent. ExecutorService;
Import java. util. concurrent. Executors;
 
Public class MyServer {
Private ServerSocket serverSocket ;//
Private ExecutorService servicePool; // Thread Pool
 
Public MyServer (int port ){
Try {
This. serverSocket = new ServerSocket (port );
This. servicePool = Executors. newFixedThreadPool (5 );
} Catch (IOException e ){
E. printStackTrace ();
}
}
 
Public static void main (String [] args ){
New MyServer (6666). service ();
}
 
Public void service (){
Int I = 0;
While (true ){
Try {
Socket socket = this. serverSocket. accept (); // receives a connection and returns the Socket object instance of a client.
This.servicePool.exe cute (new Handler (socket ));
System. out
. Println ("User" + I + "is connecting to the Server ");
I ++;
} Catch (IOException e ){
E. printStackTrace ();
This. servicePool. shutdown ();
}
}
}
 
Class Handler implements Runnable {
Private Socket socket;
 
Public Handler (Socket socket ){
This. socket = socket;
}
 
@ Override
Public void run (){
Try {
// An input stream used to obtain the content sent from the client
DataInputStream dis = new DataInputStream (
This. socket. getInputStream ());
// Content used to generate the server Preparation Response
DataOutputStream dos = new DataOutputStream (this. socket. getOutputStream ());
String str;
While (null! = (Str = dis. readUTF ())){
System. out. println (str );
If ("exit". equals (str )){
System. out. println ("the client sends an interrupt request ");
Dos. writeUTF ("the server has closed this connection .");
Dos. flush ();
// Dos. writeUTF ("exit ");//
// Dos. flush ();

Dos. close ();
Dis. close ();
Break;
}
}
 
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
}
Then, the client:
[Java]
Package qy. client;
 
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 MyClient {
 
Public static void main (String [] args ){
Try {
Socket client = new Socket ("localhost", 6666 );
MyClient me = new MyClient ();
New Thread (me. new Handler (client). start ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
 
Class Handler implements Runnable {
Private BufferedReader br;
Private DataOutputStream dos;
Private DataInputStream dis;
Private Socket socket;
Private boolean flag = true; // used to control the end of a loop
 
Public Handler (Socket s) throws IOException {
This.br = new BufferedReader (new InputStreamReader (System. in); // receives input information from the console and sends it to the server.
This. socket = s;
This. dos = new DataOutputStream (this. socket. getOutputStream (); // output stream for writing data to the server
This. dis = new DataInputStream (this. socket. getInputStream (); // gets the input stream of the data returned by the server.
}
 
@ Override
Public void run (){
While (flag ){
Try {
String str = br. readLine ();
If ("exit". equals (str) {// mark exit when the client terminates sending messages
This.br. close ();
This. dos. writeUTF (str );
This. dos. flush ();

String res = dis. readUTF ();
System. out. println (res );
 
This. dis. close ();
This. dos. close ();
This. flag = false;
} Else {
This. dos. writeUTF (str); // send one row for each read row
This. dos. flush ();
}
 
} Catch (IOException e ){
E. printStackTrace ();
}
}
}
}
}
Problems:
The first consideration is to use BufferedReader and BufferedWriter to write two-way data. However, it is found that BufferedWriter cannot immediately send the data obtained from the console to the server during fush, you can use the DataOutputStream data stream to complete two-way data transmission.

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.