简体   繁体   English

用Java发送和接收套接字消息

[英]Sending and receiving socket messages in Java

We're doing a socket programming project for our Uni.我们正在为我们的 Uni 做一个套接字编程项目。 We are developing a file sync software, and we're currently stuck with sending and receiving messages sent over socket.我们正在开发一个文件同步软件,我们目前坚持发送和接收通过套接字发送的消息。

So, when testing on local machine, code works perfectly.因此,在本地机器上测试时,代码运行良好。 But, when we simulate the server-client environment over LAN and WiFi we get null pointer exception.但是,当我们通过 LAN 和 WiFi 模拟服务器-客户端环境时,我们会得到空指针异常。 The files are being sent in chunks so only 5-10 of them pass through.文件以块的形式发送,因此只有 5-10 个文件通过。

I guess there is some issue regarding the total time needed for sending messages over socket, and that this is the reason why we get the exception.我想在通过套接字发送消息所需的总时间方面存在一些问题,这就是我们得到异常的原因。

Method for sending messages sends the message and starts the timer thread.发送消息的方法发送消息并启动定时器线程。 If no answer is received from the server within 2 seconds, the message will be sent again.如果在 2 秒内没有收到服务器的答复,消息将再次发送。 Here is the code for sending messages:下面是发送消息的代码:

public static void sendMessage(final byte[] message) {
  try {
    final Thread timer = new Thread() {                
      @Override
      public void run() {
        try {
          System.out.println("timer started");
          sleep(1500);
          System.out.println("timer timeout");
          sendMessage(message);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    };

    Thread thread = new Thread() {
      @Override
      public void run() {
        try {
          byte[] buffer = new byte[1250];
          serverByteStream.read(buffer);
          timer.stop();
        } catch (Exception e) {
        }
      }
    };

    timer.start();
    serverByteStream.write(message);
    thread.start();
  } catch (Exception e) {   
  }
}

When you recursively call sendMessage() again, you should kill the thread thread also.当您再次递归调用sendMessage()时,您也应该终止thread线程。

Please post the full stacktrace and code where the error occurs also.请发布完整的堆栈跟踪和发生错误的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM