1. 程式人生 > >java-socket通信

java-socket通信

nbsp system str sets println 連接 pub 一個 puts

Socket 客戶端實例

如下的 GreetingClient 是一個客戶端程序,該程序通過 socket 連接到服務器並發送一個請求,然後等待一個響應。

// 文件名 GreetingClient.java
 
import java.net.*;
import java.io.*;
 
public class GreetingClient
{
   public static void main(String [] args)
   {
      String serverName = args[0];
      int port = Integer.parseInt(args[1]);
      
try { System.out.println("連接到主機:" + serverName + " ,端口號:" + port); Socket client = new Socket(serverName, port); System.out.println("遠程主機地址:" + client.getRemoteSocketAddress()); OutputStream outToServer = client.getOutputStream(); DataOutputStream out
= new DataOutputStream(outToServer); out.writeUTF("Hello from " + client.getLocalSocketAddress()); InputStream inFromServer = client.getInputStream(); DataInputStream in = new DataInputStream(inFromServer); System.out.println("服務器響應: " + in.readUTF()); client.close(); }
catch(IOException e) { e.printStackTrace(); } } }

Socket 服務端實例

如下的GreetingServer 程序是一個服務器端應用程序,使用 Socket 來監聽一個指定的端口。

// 文件名 GreetingServer.java
 
import java.net.*;
import java.io.*;
 
public class GreetingServer extends Thread
{
   private ServerSocket serverSocket;
   
   public GreetingServer(int port) throws IOException
   {
      serverSocket = new ServerSocket(port);
      serverSocket.setSoTimeout(10000);
   }
 
   public void run()
   {
      while(true)
      {
         try
         {
            System.out.println("等待遠程連接,端口號為:" + serverSocket.getLocalPort() + "...");
            Socket server = serverSocket.accept();
            System.out.println("遠程主機地址:" + server.getRemoteSocketAddress());
            DataInputStream in = new DataInputStream(server.getInputStream());
            System.out.println(in.readUTF());
            DataOutputStream out = new DataOutputStream(server.getOutputStream());
            out.writeUTF("謝謝連接我:" + server.getLocalSocketAddress() + "\nGoodbye!");
            server.close();
         }catch(SocketTimeoutException s)
         {
            System.out.println("Socket timed out!");
            break;
         }catch(IOException e)
         {
            e.printStackTrace();
            break;
         }
      }
   }
   public static void main(String [] args)
   {
      int port = Integer.parseInt(args[0]);
      try
      {
         Thread t = new GreetingServer(port);
         t.run();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

java-socket通信