简体   繁体   English

Groovy和Java程序之间通过套接字进行通信

[英]communication between groovy and java programs through sockets

I am trying to write a small socket program with client side in groovy and the server side in Java. 我试图用groovy的客户端和Java的服务器端编写一个小的套接字程序。 Below is the code I wrote 下面是我写的代码

client: 客户:

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

server: 服务器:

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

When I execute both programs, Socket communication is established. 当我执行两个程序时,便建立了Socket通信。 But I get a IOException in server code when it reads from the socket ( message = in.readLine(); ) 但是当我从套接字读取message = in.readLine();时,服务器代码中出现IOExceptionmessage = in.readLine();

I guess there is some format problem in writing into socket in client. 我想在客户端写入套接字时存在一些格式问题。 But not able to figure out the exact problem. 但无法找出确切的问题。 Can anybody help? 有人可以帮忙吗?

You generally don't want to close your ServetSocket for each client connection. 通常,您不想为每个客户端连接关闭ServetSocket。 You want to do this once (or every time you start the server) then on each accept() handle the client connection and close the socket for that connection but keep the ServerSocket open until you want to stop the server. 您希望执行一次(或每次启动服务器),然后在每个accept()上处理客户端连接并关闭该连接的套接字,但保持ServerSocket打开直到您要停止服务器。

Here's a rewritten version of your example server that also creates a new Thread for each client request to handle multiple concurrent requests. 这是示例服务器的重写版本,还为每个客户端请求创建了一个新线程来处理多个并发请求。 Note that since the test client doesn't send the terminating string "bye" the connection and socket stays open. 请注意,由于测试客户端未发送终止字符串“ 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();
    }
}

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

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