-1
如何在Java中實現多線程服務器?服務器偵聽端口(例如5000)並在單獨的線程中提供連接,並持續監聽更多客戶端。Java服務器多線程
如何在Java中實現多線程服務器?服務器偵聽端口(例如5000)並在單獨的線程中提供連接,並持續監聽更多客戶端。Java服務器多線程
下面是一個典型的例子:
ServerSocket ss = new ServerSocket(port);
ExecutorService executor = Executors.newCachedThreadPool();
while(true)
{
Socket s = ss.accept();
Runnable r = new TaskImplementsRunnable(s);
executor.submit(r)
}
public class TaskImplementsRunnable implements Runnable
{
private Socket socket;
public TaskImplementsRunnable(Socket socket)
{
this.socket = socket;
}
@Override
public void run()
{
try
{
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String command;
while((command = reader.readLine()) != null)
{
if(command.equalsIgnoreCase("command 1"))
{
writer.println("This is command 1!");
}
else if(command.equalsIgnoreCase("command 2"))
{
writer.println("This is command 2!");
}
else if(command.equalsIgnoreCase("exit"))
{
break;
}
else
{
writer.println("This is unknown command!");
}
}
}
catch(IOException e)
{
e.printStackTrace();
}
try
{
writer.close();
reader.close();
}
catch(IOException e){}
}
}