我应使用服务器的哪个IP地址将客户端连接到服务器?

时间:2019-06-17 17:27:12

标签: java sockets ip

为安全起见,已隐藏IP地址。


我试图连接位于不同网络上的两个系统。我使用了公共IP地址,但无法正常工作。我应该在客户端代码中使用哪个IP地址?

我的公共IP地址:103.**.***.127。 当我将两个系统都连接到相同的wifi网络时,此代码有效。

client.java:

import javax.swing.*;
import java.net.*;
import java.util.*;
import java.awt.event.*;
import java.io.*;
class client implements ActionListener{
  JFrame f;
  Socket s;
  JButton B;
  String msg,temp;
  InetAddress inet1;
  InetSocketAddress inet;
  client() throws IOException,UnknownHostException{
    f=new JFrame ("Client");
    B=new JButton("Connect");
    f.setVisible(true);
    f.setSize(400,400);
    f.setLayout(null);
    B.setBounds(150,150,100,40);
    B.addActionListener(this);
    f.add(B);
    f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
    s=new Socket();
    inet1=InetAddress.getByName("103.**.***.127");
    inet=new InetSocketAddress(inet1,4321);
  }
  public void actionPerformed(ActionEvent e){
      if(e.getSource()==B){
          try {
        s.connect(inet);
        System.out.println("connected");
          }
          catch(Exception ex) {
        ex.printStackTrace();
          }
      }
  }
  public static void main(String[] args)throws IOException{
    client c=new client();
  }
}

server.java:

import javax.swing.*;
import java.net.*;
import java.util.*;
import java.awt.event.*;
import java.io.*;

class server implements ActionListener{
  JFrame f;
  ServerSocket ss;
  Socket s;
  JButton B;
  String msg,temp;
  JLabel j;
  server() throws IOException{
      ss=new ServerSocket(4321,1);
      s=ss.accept();
      f=new JFrame ("SERVER");
      B=new JButton("Click");
      j=new JLabel();
      f.setVisible(true);
      f.setSize(400,400);
      f.setLayout(null);
      B.setBounds(150,150,100,50);
      j.setBounds(100,100,200,50);
      B.addActionListener(this);
      f.add(B);f.add(j);
      f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
  }
  public void actionPerformed(ActionEvent e){
      if(e.getSource()==B) {
          try {
        j.setText("connected to "+s.getInetAddress());
          }
          catch(Exception ex) {
              System.out.println(ex);
          }
      }
  }
  public static void main(String[] args)throws IOException{
    server p=new server();
  }
}

我有一个例外 “ java.net.connectionexception:连接超时:....

0 个答案:

没有答案