I have two questions:
how does the 1.java server perceive client chain breakage
2. Optimal implementation of a Server supporting multiple client connections
description:
for problem 1: the problem is that in the following code, when the client breaks the chain, the, while (true) always loops, causing the output to be null
for problem 2: my current implementation is that every client connection opens a thread to handle it, which does not feel reasonable, because when thousands of clients go to connect, It is impossible to create a process in this way, seeking the optimal solution.
I hope you will not hesitate to give us your advice. Thank you. The Java server code is as follows. The function is to start a server, connect with other clients, and output directly according to the messages sent by the client:
package MyTCP;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.NonWritableChannelException;
public class Server
{
public static void main(String[] args)
{
StartListen();
}
/**
*
*/
public static void StartListen()
{
int port = 10001;
createTCP(port);
}
/**
*
* @param port
* @param address
*/
public static void createTCP(int port)
{
try
{
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("server list on 127.0.0.1:10001");
while (true)
{
Socket socket = serverSocket.accept();
new Thread(new ChildThred(socket)).start();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ChildThred implements Runnable
{
BufferedReader bufrea = null;
Socket socket = null;
public ChildThred(Socket socket)
{
this.socket = socket;
}
@Override
public void run()
{
try
{
bufrea = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true)
{
System.out.println(" : " + bufrea.readLine());
}
}
catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
finally
{
try
{
bufrea.close();
socket.close();
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
}