java网络编程----------获取Socket信息

来源:互联网 发布:西装牌子 知乎 编辑:程序博客网 时间:2024/05/19 19:44

      本例将演示网络通信程序中如何获取远程服务器和客户端的IP地址和端口号,代码如下:

 

     1.服务端代码

     

package com.zys.tcp;import java.net.ServerSocket;import java.net.Socket;import javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTextArea;public class ServerSocketFrame extends JFrame{private JTextArea textarea;private JScrollPane scrollpane;private ServerSocket server;private Socket socket;public ServerSocketFrame(){super("服务端");this.setBounds(400,200,400,300);textarea=new JTextArea();scrollpane=new JScrollPane(textarea);this.add(scrollpane);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);}public void getServer(){try {server=new ServerSocket(1978);   textarea.append("服务器套接字已经创建成功\n");while(true){textarea.append("等待客户机的连接....\n");socket=server.accept();           //等待客户端链接来实例化Socket对象textarea.append("连接成功....\n");}} catch (Exception e) {}}public static void main(String[] args) {new ServerSocketFrame().getServer();}}

    2.客户端代码:

  

package com.zys.tcp;import java.net.InetAddress;import java.net.Socket;import java.util.MissingFormatArgumentException;import javax.swing.JFrame;import javax.swing.JScrollPane;import javax.swing.JTextArea;public class ClientSocketFrame extends JFrame{private JTextArea textarea;private JScrollPane scrollpane;private Socket socket;private String ip="127.0.0.1";public ClientSocketFrame(){super("客户端");        this.setBounds(400,200,400,300);textarea=new JTextArea();scrollpane=new JScrollPane(textarea);this.add(scrollpane);this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);this.setVisible(true);}private void connect(){textarea.append("尝试连接......\n");try {socket=new Socket(ip,1978);textarea.append("完成连接......\n");InetAddress netAddress=socket.getInetAddress();    //获得远程服务器的地址String netIp=netAddress.getHostAddress();          //获得远程服务器的IP地址int netPort=socket.getPort();                      //获得远程服务器的端口号InetAddress localAddress=socket.getLocalAddress();   //获得客户端地址String  localIp=localAddress.getHostAddress();       //获得客户端的IP地址int localPort=socket.getLocalPort();                 //获得客户端的端口textarea.append("远程服务器的IP地址"+netIp+"\n");textarea.append("远程服务器的端口"+netPort+"\n");textarea.append("客户端的IP地址"+localIp+"\n");textarea.append("客户端的端口"+localPort+"\n");} catch (Exception e) {}}public static void main(String[] args) {new ClientSocketFrame().connect();}}

    运行结果如下图:

 


使用的方法总结:

      1.Socket类的getIntAddress()可以获得远程服务器的地址,进而获得远程服务器的IP地址和Port

       2.Socket类的getLocalAddress()方法可以获得客户端的地址,进而获得本地客户端的IP地址和Port