将多个客户端连接到一台服务器
我试图将所有客户端连接到一台服务器。我做了一些研究,发现最简单的方法是为连接到服务器的每个客户端创建一个新线程。但是我已经停留在客户端断开连接并重新连接的部分。将多个客户端连接到一台服务器
客户
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Test {
private static int port = 40021;
private static String ip = "localhost";
public static void main(String[] args) throws UnknownHostException,
IOException {
String command, temp;
Scanner scanner = new Scanner(System.in);
Socket s = new Socket(ip, port);
while (true) {
Scanner scanneri = new Scanner(s.getInputStream());
System.out.println("Enter any command");
command = scanner.nextLine();
PrintStream p = new PrintStream(s.getOutputStream());
p.println(command);
temp = scanneri.nextLine();
System.out.println(temp);
}
}
}
服务器
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class MainClass {
public static void main(String args[]) throws IOException {
String command, temp;
ServerSocket s1 = new ServerSocket(40021);
while (true) {
Socket ss = s1.accept();
Scanner sc = new Scanner(ss.getInputStream());
while (sc.hasNextLine()) {
command = sc.nextLine();
temp = command + " this is what you said.";
PrintStream p = new PrintStream(ss.getOutputStream());
p.println(temp);
}
}
}
}
当我连接,一旦它工作正常,但只要我断开客户端,并尝试重新连接(或连接第二个客户端),它并没有给一个错误或任何它只是不起作用。我试图尽可能保持基本。
我希望有人能够帮助我。提前致谢。
您的服务器目前在一个时间只能处理1的客户端,使用线程为每个客户端,请修改服务器代码: -
public static void main(String[] args) throws IOException
{
ServerSocket s1 = new ServerSocket(40021);
while (true)
{
ss = s1.accept();
Thread t = new Thread()
{
public void run()
{
try
{
String command, temp;
Scanner sc = new Scanner(ss.getInputStream());
while (sc.hasNextLine())
{
command = sc.nextLine();
temp = command + " this is what you said.";
PrintStream p = new PrintStream(ss.getOutputStream());
p.println(temp);
}
} catch (IOException e)
{
e.printStackTrace();
}
}
};
t.start();
}
}
是的,但这并不能解决问题。它没有例外。 –
@JesseVlietveld,当你的主函数抛出IOException异常时,当客户端断开连接,因为异常被抛出关闭服务器的主函数时,程序退出,你可以删除它并单独放置一个try catch,或者可以不必要地将它保留在那里并把它放在 – 2016-03-04 20:16:09
我不认为你理解我。问题是它没有给出错误或例外。它只是没有显示任何东西。我会更详细地更新我的文章。 –
所以,根据你的研究,你应该已经创建了每一个新的线程客户端连接在服务器上。你正在做的那个部分在哪里? – RealSkeptic
@RealSkeptic我一直在编程大学几个月了,我不明白线程。所以我希望有人能为我解释。 –