位置:首页 > Java技术 > java实例在线教程 > Java连接套接字

Java连接套接字

如何使服务器允许连接到套接字-socket 6123? 

解决方法

下面的示例演示如何使用ServerSocket类的server.accept()方法和Socket类的sock.getInetAddress()方法使一个服务器允许连接到套接字- socket 6123。

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketDemo {
   public static void main(String[] args) {
      try {
         ServerSocket server = new ServerSocket(6123);
         while (true) {
            System.out.println("Listening");
            Socket sock = server.accept();
            InetAddress addr = sock.getInetAddress();
            System.out.println("Connection made to "
            + addr.getHostName()
            + " (" + addr.getHostAddress() + ")");
            pause(5000);
            sock.close();
         }
      }
	  catch (IOException e) {
         System.out.println("Exception detected: " + e);
      }
   }
   private static void pause(int ms) {
      try {
         Thread.sleep(ms);
      }
      catch (InterruptedException e) {
      }
   }
}

结果

上面的代码示例将产生以下结果。

Listening
Terminate batch job (Y/N)? n 
Connection made to 112.63.21.45