为了账号安全,请及时绑定邮箱和手机立即绑定

Java套接字自动通信

Java套接字自动通信

偶然的你 2021-05-14 17:08:11
服务器和客户端之间的通讯出现问题。我试图找出一种自动通信的方式,因为它们必须交换一些参数。但是,使用我编写的代码,服务器要么在客户端确认消息后继续向客户端发送相同的消息,要么客户端什么也没收到。套接字和所有东西都已经设置好了。函数sendString()和receiveString()在两个代码示例中都是相同的。是否有适当的方法来做到这一点?我不明白为什么这行不通...服务器:String buffer;    while(true){        buffer = client.receiveString();        if(buffer != null && buffer.equals("ready")){            System.out.println("Client is ready");            client.sendString("ready");            while(true){                buffer = client.receiveString();                if(buffer != null && buffer.equals("k")){                    System.out.println("stopped");                    break;                }            }            break;        }    }public String receiveString() throws IOException{         //From the client class    if(dataIn.available() > 0){        int length = dataIn.readInt();        byte[] b = new byte[length];        dataIn.readFully(b, 0, b.length);        return new String(b, Charset.forName("UTF-8"));    }    return null;}public void sendString(String msg) throws IOException{    byte[] b = msg.getBytes(Charset.forName("UTF-8"));    dataOut.writeInt(b.length);    dataOut.write(b);}客户:String buffer;while(true){    sendString("ready");    buffer = receiveString();    if(buffer!=null)        System.out.println(buffer);    if(buffer != null && buffer.equals("ready")){           System.out.println("Server is ready");        sendString("k");        break;    }}
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 142 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信