服务器和客户端不能相互通信



我正试图使某种登录系统,但服务器和客户端不会相互交谈。我不太确定他们为什么不互相交谈,但任何帮助都是感激的。

p。我的路由器上的端口设置正确。

客户

public class Clients implements Runnable
{
String ip = "localhost";
int port = 25565;
Socket client;
static Thread thread;
boolean setup = false;
BufferedReader br;
PrintWriter pw;
public static void main(String[] args)
{
    thread = new Thread(new Clients());
    thread.start();
}
public void run()
{
    while(!setup)
    {
        try {
            client = new Socket(ip,port);
            setup = true;
        } catch (IOException e) {
            setup = false;
        }
    }
    try {
        br = new BufferedReader(new InputStreamReader(client.getInputStream()));
        pw = new PrintWriter(client.getOutputStream(),true);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    pw.flush();
    pw.write("client");
    while(true);
}
}
服务器

public class Server implements Runnable
{
int port = 25565;
String input;
ServerSocket server;
Socket clients;
BufferedReader br;
PrintWriter pw;
boolean setup = false;
static Thread thread;
public static void main(String[] args)
{
    thread = new Thread(new Server());
    thread.start();
}
public void run()
{
    try {
        server = new ServerSocket(port);
        clients = server.accept();
        br = new BufferedReader(new InputStreamReader(clients.getInputStream()));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        System.out.println("getting input");
        while((input = br.readLine()) != null)
        {
            System.out.println(input);
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}

应该先写,再刷

pw.write("clientn");
pw.flush();

还将n放在您正在编写的行中,因为在客户端中您正在执行br.readline().,因此它将等待直到新的行可用。

我看到两个问题。首先,pw.flush应该在pw.write之后调用。第二个是服务器正在等待readLine(),它只会在遇到行结束时返回。您应该更改Clients以调用pw.write("clientsn"),并添加换行符。

最新更新