从http://pirate.shu.edu/~wachsmut/Teaching/CSAS2214/Virtual/Lectures/chat-client-server.html的第3步中列出的套接字服务器可以进行干净构建(java版本为“ 1.7.0_02”),并且可以正常运行,但是可以退出而不会出现错误,而不必等待接受客户端。
更新了缺少arg代码的ChatServer:
聊天服务器:
import java.net.*;
import java.io.*;
public class ChatServer implements Runnable
{ private ServerSocket server = null;
private Thread thread = null;
private ChatServerThread client = null;
public ChatServer(int port)
{ try
{ System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
start();
}
catch(IOException ioe)
{ System.out.println(ioe); }
}
public void run()
{ while (thread != null)
{ try
{ System.out.println("Waiting for a client ...");
addThread(server.accept());
}
catch(IOException ie)
{ System.out.println("Acceptance Error: " + ie); }
}
}
public void addThread(Socket socket)
{ System.out.println("Client accepted: " + socket);
client = new ChatServerThread(this, socket);
try
{ client.open();
client.start();
}
catch(IOException ioe)
{ System.out.println("Error opening thread: " + ioe); }
}
public void start() {
thread = new Thread(this);
thread.start();
}
public void stop() { /* no change */ }
public static void main(String args[]) {
ChatServer server = null;
if (args.length != 1)
System.out.println("Usage: java ChatServer port");
else
server = new ChatServer(Integer.parseInt(args[0]));
}
}
ChatServerThread:
import java.net.*;
import java.io.*;
public class ChatServerThread extends Thread
{ private Socket socket = null;
private ChatServer server = null;
private int ID = -1;
private DataInputStream streamIn = null;
public ChatServerThread(ChatServer _server, Socket _socket)
{ server = _server; socket = _socket; ID = socket.getPort();
}
public void run()
{ System.out.println("Server Thread " + ID + " running.");
while (true)
{ try
{ System.out.println(streamIn.readUTF());
}
catch(IOException ioe) {
System.out.println(ioe.getMessage());
}
}
}
public void open() throws IOException
{ streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
public void close() throws IOException
{ if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
}
}
最佳答案
编辑:用一个可行的解决方案更新我的答案。
在您的ChatServer
类中更改这些方法,以使它们像这样
public void start() {
thread = new Thread(this);
thread.start();
}
public void stop() {
// You should implement this too
}
public static void main(String args[]) {
// Instantiate a CharServer with the listening port 9191
ChatServer chatServer = new ChatServer(9191);
// CharServer.start() should not be confused with Thread.start();
// This calls our custom method up above, which includes a call to
// Thread(ChatServer).start();
chatServer.start();
}
其中9191是我填写的端口号。
执行
CharServer
#main方法将产生以下输出并保持活动状态Binding to port 9191, please wait ...
Server started: ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=9191]
Waiting for a client ...
Waiting for a client ...
为了功能性,还应该实现
stop()
方法。