You can use a value similar to while (true) input. readByte () to retrieve the data sent by the client. Use output writeByte to send data like a client.
The server socket is generated by using the serverSocket. accept () method.
Use this class to implement the thread pool.
For example, the following code provides a simple function, that is, the client sends a byte, and the server reads the data sent by the client and prints it.
| The code is as follows: |
Copy code |
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;
Class NetworkService implements Runnable {
Private final ServerSocket serverSocket;
Private final ExecutorService pool;
Public NetworkService (int port, int poolSize) throws IOException {
ServerSocket = new ServerSocket (port );
Pool = Executors. newFixedThreadPool (poolSize );
}
Public void run () {// run the service
Try {
For (;;){
Pool.exe cute (new Handler (serverSocket. accept ()));
}
} Catch (IOException ex ){
Pool. shutdown ();
}
}
Public static void main (String [] args ){
NetworkService ns = null;
Try {
Ns = new NetworkService (400, 5 );
} Catch (IOException e ){
E. printStackTrace ();
}
New Thread (ns). start ();
}
}
Class Handler implements Runnable {
Private final Socket socket;
Private DataInputStream input;
Private DataOutputStream output;
Handler (Socket socket ){
This. socket = socket;
Try {
Input = new DataInputStream (socket. getInputStream ());
Output = new DataOutputStream (socket. getOutputStream ());
System. out. println ("new connect ");
} Catch (Exception e ){
E. printStackTrace ();
}
}
Public void run (){
Int data;
While (true ){
Try {
Data = input. readByte ();
System. out. println (data );
} Catch (IOException e ){
Break;
}
}
System. out. println ("close ");
Try {
Input. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
Try {
Output. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
Try {
Socket. close ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
} |
Client
| The code is as follows: |
Copy code |
|
Var socket: Socket = new Socket (400 );
Socket. addEventListener ("connect", function (): void {socket. writeByte (100 )}); |