Java TCP服務(wù)器

2018-02-28 16:57 更新

Java網(wǎng)絡(luò)教程 - Java TCP服務(wù)器


ServerSocket 類的一個(gè)對(duì)象表示Java中的TCP服務(wù)器套接字。

ServerSocket 對(duì)象可以接受來(lái)自遠(yuǎn)程客戶端的連接請(qǐng)求。

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

例子

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

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

您可以通過(guò)使用以下任何構(gòu)造函數(shù)在一個(gè)步驟中組合create,bind和listen操作。

等待隊(duì)列大小的默認(rèn)值為50。

本地IP地址的缺省值是通配符地址,即服務(wù)器計(jì)算機(jī)的所有IP地址。

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

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

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

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

要接受遠(yuǎn)程連接請(qǐng)求,請(qǐng)調(diào)用服務(wù)器套接字上的 accept()方法。

accept()方法調(diào)用阻塞執(zhí)行,直到來(lái)自遠(yuǎn)程客戶端的請(qǐng)求到達(dá)其等待隊(duì)列。


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

Socket類包含兩個(gè)方法 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()方法關(guān)閉連接。關(guān)閉套接字還會(huì)關(guān)閉其輸入和輸出流。

activeSocket.close();

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

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();
    }

  }
}


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)