我正在尝试将所有客户端连接到一台服务器。我进行了一些研究,发现最简单的方法是为连接到服务器的每个客户端创建一个新线程。但是我已经停留在客户端断开连接并重新连接的部分。
客户
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();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句