java - groovy和java程序之间通过socket进行通信

标签 java sockets groovy client

我正在尝试编写一个小型套接字程序,客户端使用groovy,服务器端使用Java。下面是我写的代码

客户:

def s = new Socket("localhost", 4444);
s << "Server before withStreams\n";
s.withStreams { input, output ->
  println"Sending message1" 
  output << "server message1\n"
}
s.close();

服务器:

import java.io.*;
import java.net.*;

public class Logger{
  ServerSocket providerSocket;
  Socket connection = null;
  BufferedReader in;
  String message="InitialMessage";
  Logger(){}

  void run()
  {
    try{
      providerSocket = new ServerSocket(4444, 10);
      try{
        Thread.sleep(1000);
      }
      catch(InterruptedException ie)
      {
        System.out.println("Sleep Interrupted");
      }
      System.out.println("Waiting for connection");
      connection = providerSocket.accept();
      System.out.println("Connection received from " + connection.getInetAddress().getHostName());

      in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
      do{
        if(in.ready())
        {
          try{
            System.out.println(in.read());
            message = in.readLine();
            System.out.println("client>" + message);
          }
          catch(IOException e)
          {
            System.out.println(e);
            e.printStackTrace();
            break;
          }
        }
      } while(!message.equals("bye"));
    }
    catch(IOException ioException){
      ioException.printStackTrace();
    }
    finally{
      //4: Closing connection
      try{
        in.close();
        providerSocket.close();
      }
      catch(IOException ioException){
        ioException.printStackTrace();
      }
    }
  }

  public static void main(String args[])
  {
    Logger server = new Logger();
    while(true){
      server.run();
    }
  }
}

当我执行这两个程序时,套接字通信就建立了。但是当从套接字读取时,我在服务器代码中收到 IOException (message = in.readLine();)

我猜想在客户端写入套接字时存在一些格式问题。但无法找出具体的问题所在。有人可以帮忙吗?

最佳答案

您通常不希望为每个客户端连接关闭 ServetSocket。您希望执行一次此操作(或每次启动服务器时),然后在每个accept() 上处理客户端连接并关闭该连接的套接字,但保持 ServerSocket 打开,直到您想要停止服务器为止。

这是示例服务器的重写版本,它还为每个客户端请求创建一个新线程来处理多个并发请求。请注意,由于测试客户端不会发送终止字符串“bye”,因此连接和套接字保持打开状态。

import java.io.*;
import java.net.*;

public class Logger {
    private ServerSocket providerSocket;

    Logger() {

    }

    public void start() {
        try {
            providerSocket = new ServerSocket(4444, 10);
            while (true) {
                System.out.println("Waiting for connection");
                Socket connection = providerSocket.accept();
                new Thread(new Job(connection)).start();
            }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (providerSocket != null) {
            System.out.println("Stopping server");
            try {
                providerSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    }

    static class Job implements Runnable {
        final Socket connection;
        private static int id;
        private int clientId = ++id;

        public Job(Socket connection) {
            this.connection = connection;
        }

        public void run() {
            BufferedReader in = null;
            try {
                System.out.println("Connection " + clientId + " received from " + connection.getInetAddress().getHostName());
                in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String message = "InitialMessage";
                do {
                    if (in.ready()) {
                        try {
                            // not sure why want to read one character then read the line
                            //int ch = in.read();
                            //System.out.println(ch);
                            // -1 if the end of the stream has been reached
                            //if (ch == -1) break;
                            message = in.readLine();
                            // null if the end of the stream has been reached
                            if (message == null) break;
                            System.out.println("client>" + message);
                        } catch (IOException e) {
                            System.out.println(e);
                            e.printStackTrace();
                            break;
                        }
                    }
                } while (!message.equals("bye"));
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                //4: Closing connection
                System.out.println("Close connection " + clientId);
                if (in != null)
                    try {
                        in.close();
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String args[]) {
        Logger server = new Logger();
        server.start();
    }
}

关于java - groovy和java程序之间通过socket进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10302796/

相关文章:

java - 如何使用 selenium webdriver 进行水平滚动

java - hashandlers在gwt中是什么意思

JAVA 电子邮件消息 - 剪辑引用行

c++ - 使用QTcpSocket实现连续快速使用

node.js - Socket.io在Ubuntu 16.04上不起作用

grails - 如何在Spock集成测试中为每个测试类设置transactionnal选项?

groovy - 这个,所有者,Groovy 闭包中的委托(delegate)

grails - Grails Layout,该怎么做?

Java匿名内部类调用封闭类型父类(super class)型方法

c - udp socket编程文件传输