简体   繁体   English

用于客户端和服务器通信的Java套接字程序自动重新连接

[英]Java socket program for client and server communication auto reconnect

I want to develop client and server communication and I have written some code for client and server but once the client and server connect, there's no need to reconnect again and again. 我想开发客户端和服务器之间的通信,并且已经为客户端和服务器编写了一些代码,但是一旦客户端和服务器连接,就不需要一次又一次地重新连接。 However, in my current code they keep re-connecting again and again. 但是,在我当前的代码中,它们不断地重新连接。

  1. InetAddress host = InetAddress.getLocalHost();
  2. Socket s = new Socket(host.getHostName(), 4321);

The second line will create new connection each time and this is the problem I'm trying to solve (they only need to connect once). 第二行每次都会创建新的连接,这是我要解决的问题(它们只需连接一次)。

ClientClass.java ClientClass.java

public class CientClass {

public static void main(String[] args)  
  {
    System.out.println("CLIENT SITE");
    while (true) {
        try {
            InetAddress host = InetAddress.getLocalHost();
            Socket s = new Socket(host.getHostName(), 4321);
            DataOutputStream dout = new DataOutputStream(s.getOutputStream());
            Scanner sc = new Scanner(System.in);
            System.out.println("Ener for server:");
            String data = sc.next();
            dout.writeUTF(data);
        }
        catch (Exception e) {
            System.out.println(e);
            e.printStackTrace();
        }
    }
  }
}

Serverclass.java 服务器类

public class Serverclass {

public static void main(String[] args) {
    System.out.println("SERVER SITE");
    while (true) {
        try {
            ServerSocket ss = new ServerSocket(4321);
            Socket s = ss.accept();
            DataInputStream din = new DataInputStream(s.getInputStream());
            String str = (String) din.readUTF();
            System.out.println("message:" + str);
            ss.close();
        }
        catch (Exception e) {
            System.out.println(e);
            e.printStackTrace();
        }
    }
  }
}

The clientClass reads commands from the console and sends to the server but it should not keep reconnecting after the initial connection. clientClass从控制台读取命令并将其发送到服务器,但在初始连接后不应保持重新连接。

And in a situation like restart the server and the client should connect automatically and and client should be able to send the commands to the server. 在重新启动服务器和客户端的情况下,客户端应自动连接,并且客户端应能够将命令发送到服务器。

I think I don't need to change the serverclass code. 我认为我不需要更改服务器类代码。 Only need to change the clientClass code. 只需要更改clientClass代码。 How? 怎么样?

Okay so there are two main reasons why there will always be established a new connection. 好的,有两个主要原因为什么总会建立一个新的连接。

First of all for every cycle of your while(true) loop in your ServerClass you're creatinga new server socket and await a new connection by calling ServerSocket.accept() which is also a blocking operation, which means the server keeps blocking until a new connection arrives. 首先,在ServerClass中while(true)循环的每个循环中,您都在创建一个新的服务器套接字,并通过调用ServerSocket.accept()来等待新的连接,这也是一个阻塞操作,这意味着服务器一直阻塞直到出现新的连接到来。

The second reason for this behaviour is, that you are always enforcing a new connection from your ClientClass by creating a new socket. 此行为的第二个原因是,您总是通过创建新的套接字来从ClientClass强制执行新的连接。 Sockets establish end-to-end-connections. 套接字建立端到端连接。 Once created and conencted you don't have to make another one. 创建并合并后,您无需再制作一个。

The most convientient fix for you would be to replace the while(true) loop so that it only covers the real send/receive logic in some way like this: 对您来说,最方便的解决方法是替换while(true)循环,以便它仅以如下方式覆盖实际的发送/接收逻辑:

ClientClass 客户类别

  try
  {
    InetAddress host = InetAddress.getLocalHost();
    Socket s = new Socket( host.getHostName(), 4321 );
    DataOutputStream dout = new DataOutputStream( s.getOutputStream() );
    while ( isAlive )
    {
      Scanner sc = new Scanner( System.in );
      System.out.println( "Ener for server:" );
      String data = sc.next();
      dout.writeUTF( data );
    }
  }
  catch ( Exception e )
  {
    System.out.println( e );
    e.printStackTrace();
  }

ServerClass 服务器类

try
      {
        ServerSocket ss = new ServerSocket( 4321 );
        Socket s = ss.accept();
        DataInputStream din = new DataInputStream( s.getInputStream() );
        while ( isAlive )
        {
          String str = (String) din.readUTF();
          System.out.println( "message:" + str );
        }
        ss.close();
      }
      catch ( Exception e )
      {
        System.out.println( e );
        e.printStackTrace();
      }

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

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