[英]Java Socket Multithreading Server; Chatting
Server.java:
private Socket connection;
private int ID;
public static void main(String[] args) {
int port = 19999;
int count = 0;
try{
ServerSocket socket1 = new ServerSocket(port);
System.out.println("Server Initialized");
while (true) {
Socket connection = socket1.accept();
Runnable runnable = new Server(connection, ++count);
Thread thread = new Thread(runnable);
thread.start();
}
}
catch (Exception e) {}
}
Server(Socket s, int i) {
this.connection = s;
this.ID = i;//could use a client name as it is individual id for each thread.?
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
PrintWriter out = new PrintWriter(connection.getOutputStream(), true);
String inputLine;
while ((inputLine = in.readLine()) != null) {
Process p = new Process();
String output = p.input(inputLine);
out.println(output);
}
}
}
catch (Exception e) {
System.out.println(e);
}
finally {
try {
connection.close();
}
catch (IOException e){}
}
}
}
运行时,它会创建一个服务器,当客户端连接到该服务器时,该服务器会为其创建一个线程,以便它可以一次处理多个客户端。
但是代码:
while ((inputLine = in.readLine()) != null) {
Process p = new Process();
String output = p.input(inputLine);
out.println(output);
}
循环BufferedReader以获取客户端提供的所有输入。 当接收程序处理时,然后将回复发送回客户端以进行打印。
我如何获得它,以便我可以在与第一个同时通过客户端发送/获取另一个问题?
例如
“用户:您好,您好吗?” “计算机:我很好,你好吗?” “用户:我很好”“计算机:很高兴听到”
工作正常。 但:
“用户:是1 + 1吗?” “计算机:1 + 1 = 2”“计算机:还有其他问题吗?” “用户:好吗?”
才不是。
如何做到这一点,以便服务器给出多个答案,而不必等待其他输入?
如果我在server.java中将输出设置为字符串,这将很容易,但是每次我尝试访问该字符串以更改它时(通过使用
Server s = new Server(); s.output = "stuff";
),如代码所示,它只是制造了一个新的线程服务器。 我怎样才能访问已经建立的线程?
您必须将客户端线程存储在一种映射中,如果需要将消息发送到另一个线程,则可以查找该映射并获取对该另一个线程的引用,然后从那里发送消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.