所以我不知道誰去創建一個多線程服務器。我的客戶端和服務器一起工作良好,但無法正確引入多個客戶端。這裏是我的服務器代碼:單客戶端到多客戶端支持:在java中的多線程轉換
package dod;
import java.net.*;
import java.io.*;
import dod.game.GameLogic;
public class Server{
Server(GameLogic game, int port) throws IOException{
ServerSocket ss = null;
Socket sock = null;
try{
ss = new ServerSocket(4444);//port no.
while(true){
try{
sock = ss.accept();
ClientThread thread = new ClientThread(game, sock);
System.out.println("Adding new player...");
thread.run();
}catch(final Exception e) {
System.err.println(e.getMessage());
System.exit(1);
}
}
}catch(Exception d){
System.out.println(d);
}finally{
if(ss!=null){
ss.close();
}
}
}
}
這裏是我的線程類:
package dod;
import java.io.*;
import java.net.Socket;
import dod.game.GameLogic;
import dod.game.PlayerListener;
public class ClientThread extends CommandLineUser implements PlayerListener, Runnable{
DataInputStream in;
PrintStream out;
// The game which the command line user will operate on.
// This is private to enforce the use of "processCommand".
ClientThread(GameLogic game, Socket sock) {
super(game);
try{
in = new DataInputStream(sock.getInputStream());
out = new PrintStream(sock.getOutputStream());
}catch(IOException ioe){
System.out.println(ioe);
}
game.addPlayer(this);
}
/**
* Constantly asks the user for new commands
*/
public void run() {
System.out.println("Added new human player.");
// Keep listening forever
while(true){
try{
// Try to grab a command from the command line
final String command = in.readLine();;
// Test for EOF (ctrl-D)
if(command == null){
System.exit(0);
}
processCommand(command);
}catch(final RuntimeException e){
System.err.println(e.toString());
System.exit(1);
} catch (final IOException e) {
System.err.println(e.toString());
System.exit(1);
}
}
}
/**
* Outputs a message to the player
*
* @param message
* the message to send to the player.
*/
public void outputMessage(String message) {
out.print(message);
}
}
不要求新的代碼,例如,只需要指針,以什麼我需要做的有在多個客戶端連接同時!感謝任何有幫助的人!
您是否在向其他客戶端發送有關新客戶端連接的消息? –
'DataInputStream.readLine()'是一個不推薦的方法。不要使用它。 – Braj
你必須閱讀,如何開始一個線程?您正在直接調用run方法。調用start(),它將在內部調用run()。 – Braj