在 java 中连接两台计算机进行客户端服务器通信

Connecting two computers for client server communication in java

此代码是关于 java 中的客户端和服务器通信的。我可以 运行 我的 PC 中的两个代码,并且可以连接客户端和服务器。但是我将如何连接 2 台计算机作为客户端和服务器。这是我的服务器和客户端代码如下:

我的服务器1

//code for server
import java.io.*;
import java.net.*;

public class MyServer1
{
    ServerSocket ss;
    Socket s;
    DataInputStream dis;
    DataOutputStream dos;
    public MyServer1()
    {
        try
        {
            System.out.println("Server Started");
            ss=new ServerSocket(10);
            s=ss.accept();
            System.out.println(s);
            System.out.println("CLIENT CONNECTED");
            dis= new DataInputStream(s.getInputStream());
            dos= new DataOutputStream(s.getOutputStream());
            ServerChat();
        }
        catch(Exception e)
        {
             System.out.println(e);
        }
    }

    public static void main (String as[])
    {
         new MyServer1();
    }

    public void ServerChat() throws IOException
    {
         String str, s1;
         do
         {
             str=dis.readUTF();
             System.out.println("Client Message:"+str);
             BufferedReader br=new BufferedReader(new   InputStreamReader(System.in));
             s1=br.readLine();
             dos.writeUTF(s1);
             dos.flush();
         }
         while(!s1.equals("bye"));
    }
}

我的客户1

//code for client
import java.io.*;
import java.net.*;

public class MyClient1
{
    Socket s;
    DataInputStream din;
    DataOutputStream dout;
    public MyClient1()
    {
         try
         {
             //s=new Socket("10.10.0.3,10");
             s=new Socket("localhost",10);
             System.out.println(s);
             din= new DataInputStream(s.getInputStream());
             dout= new DataOutputStream(s.getOutputStream());
             ClientChat();
         }
         catch(Exception e)
         {
             System.out.println(e);
         }
     }
     public void ClientChat() throws IOException
     {
           BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
           String s1;
           do
           {
               s1=br.readLine();
               dout.writeUTF(s1);
               dout.flush();
               System.out.println("Server Message:"+din.readUTF());
           }
           while(!s1.equals("stop"));
    }
    public static void main(String as[])
    {
        new MyClient1(); 
    }
}

客户端只需要服务器的IP。
你必须找出服务器的IP并告诉客户端,例如:

String serverName = "IP of server comes here";  // Indicating the place to put Server's IP
s = new Socket(serverName, 10);

服务器无需更改。

创建Socket 实例时,您只需输入服务器的IP。 我建议你按照步骤

1) 在您要用作服务器的任何一台计算机上启动热点 2)在第二台电脑上启动wifi并连接我们刚刚启动的热点。 3) 现在转到共享中心并单击您连接的网络并检查详细信息并复制 dns 服务器 ip 并将其粘贴到客户端程序中