【问题标题】:Server and Client wont talk to each other服务器和客户端不会互相交谈
【发布时间】:2014-10-06 06:28:44
【问题描述】:

我正在尝试制作某种登录系统,但服务器和客户端不会相互通信。我不太确定他们为什么不互相交谈,但感谢任何帮助。

P.S 端口在我的路由器上设置正确。

客户

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();
    }
}
}

【问题讨论】:

  • 你的意思是服务器无法读取“客户端”?
  • 他们似乎连接得很好,他们都没有给我一个例外,但是当我通过流发送一些东西时,“服务器”不会读取它
  • 这里有很多有问题的代码。首先,while(true) 什么都不做;你没有给它一个身体。其次,您只在服务器上初始化了输入流,但在客户端上初始化了输入和输出流。我猜客户端正在等待初始化你没有在服务器上初始化的流。
  • 只是想知道如果您连接到“localhost”,为什么需要路由器?您还在服务器上运行服务器应用程序,在客户端计算机上运行客户端应用程序吗?
  • “localhost”是这样我可以更改它并给我的朋友稍后测试它,而 true 只是为了保存程序,我无法让服务器读取输入流首先,如果它没有输出流,那为什么重要呢?

标签: java sockets bufferedreader serversocket printwriter


【解决方案1】:

你应该先写然后刷新

pw.write("client\n");
pw.flush();

还将 \n 放在您正在编写的行中,因为在您正在执行的客户端中 br.readline(). 所以它会等到有新行可用。

【讨论】:

  • 谢谢你,我知道我错过了一些非常简单的东西!
【解决方案2】:

我看到了两个问题。首先是pw.flush应该在pw.write之后调用。二是服务器正在等待readLine(),只有遇到行尾才会返回。您应该更改Clients 以调用pw.write("clients\n"),添加换行符。

【讨论】:

    猜你喜欢
    • 2016-09-22
    • 1970-01-01
    • 2016-07-28
    • 1970-01-01
    • 2015-12-25
    • 1970-01-01
    • 2013-10-27
    • 2017-12-06
    • 1970-01-01
    相关资源
    最近更新 更多