Java TCP服務器

2018-02-28 16:57 更新

Java網絡教程 - Java TCP服務器


ServerSocket 類的一個對象表示Java中的TCP服務器套接字。

ServerSocket 對象可以接受來自遠程客戶端的連接請求。

我們可以使用no-args構造函數創(chuàng)建一個未綁定的服務器套接字,并使用其bind()方法將其綁定到本地端口和本地IP地址。

例子

以下代碼顯示如何創(chuàng)建服務器套接字:

import java.net.InetSocketAddress;
import java.net.ServerSocket;

public class Main {
  public static void main(String[] argv) throws Exception {
    // Create an unbound server socket
    ServerSocket serverSocket = new ServerSocket();

    // Create a socket address object
    InetSocketAddress endPoint = new InetSocketAddress("localhost", 12900);

    // Set the wait queue size to 100
    int waitQueueSize = 100;

    // Bind the server socket to localhost and at port 12900 with
    // a wait queue size of 100
    serverSocket.bind(endPoint, waitQueueSize);

  }
}

例2

您可以通過使用以下任何構造函數在一個步驟中組合create,bind和listen操作。

等待隊列大小的默認值為50。

本地IP地址的缺省值是通配符地址,即服務器計算機的所有IP地址。

ServerSocket(int port)
ServerSocket(int port, int waitQueueSize)
ServerSocket(int port, int waitQueueSize,  InetAddress  bindAddr)

您可以將套接字創(chuàng)建和綁定步驟合并為一個語句。

以下代碼顯示如何在端口12900創(chuàng)建服務器套接字,其中100作為等待隊列大小,并在localhost回送地址。

ServerSocket serverSocket  = new ServerSocket(12900, 100, InetAddress.getByName("localhost"));

要接受遠程連接請求,請調用服務器套接字上的 accept()方法。

accept()方法調用阻塞執(zhí)行,直到來自遠程客戶端的請求到達其等待隊列。


The following code calls on ServerSocket will wait  for a  new remote  connection request.
Socket activeSocket = serverSocket.accept();

Socket類包含兩個方法 getInputStream() getOutputStream()用于讀取和寫入連接的套接字。

BufferedReader br  = new BufferedReader(new InputStreamReader(activeSocket.getInputStream()));
BufferedWriter bw  = new BufferedWriter(new OutputStreamWriter(activeSocket.getOutputStream()));
String s = br.readLine();
bw.write("hello"); 
bw.flush();

最后,使用套接字的close()方法關閉連接。關閉套接字還會關閉其輸入和輸出流。

activeSocket.close();

以下代碼顯示如何創(chuàng)建服務器套接字。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {
  public static void main(String[] args) throws Exception {
    ServerSocket serverSocket = new ServerSocket(12900, 100,
        InetAddress.getByName("localhost"));
    System.out.println("Server started  at:  " + serverSocket);

    while (true) {
      System.out.println("Waiting for a  connection...");

      final Socket activeSocket = serverSocket.accept();

      System.out.println("Received a  connection from  " + activeSocket);
      Runnable runnable = () -> handleClientRequest(activeSocket);
      new Thread(runnable).start(); // start a new thread
    }
  }

  public static void handleClientRequest(Socket socket) {
    try{
      BufferedReader socketReader = null;
      BufferedWriter socketWriter = null;
      socketReader = new BufferedReader(new InputStreamReader(
          socket.getInputStream()));
      socketWriter = new BufferedWriter(new OutputStreamWriter(
          socket.getOutputStream()));

      String inMsg = null;
      while ((inMsg = socketReader.readLine()) != null) {
        System.out.println("Received from  client: " + inMsg);

        String outMsg = inMsg;
        socketWriter.write(outMsg);
        socketWriter.write("\n");
        socketWriter.flush();
      }
      socket.close();
    }catch(Exception e){
      e.printStackTrace();
    }

  }
}


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號