簡體   English   中英

Groovy和Java程序之間通過套接字進行通信

[英]communication between groovy and java programs through sockets

我試圖用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();
    }
  }
}

當我執行兩個程序時,便建立了Socket通信。 但是當我從套接字讀取message = in.readLine();時,服務器代碼中出現IOExceptionmessage = 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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM