Java Socket程式設計系列(一)開發一次性會話的Server和Client

indexman發表於2017-12-24

關於什麼是Socket:


A socket is one end-point of a two-way communication link between two programs running on the network.

Socket是網路上執行的2個程式之間通訊連結的終點。說白了就是代表一條通訊鏈路的兩端。


Socket classes are used to represent the connection between a client program and a server program.

Socket類用來代表客戶端程式和伺服器端程式的連線。


The java.net package provides two classes--Socket and ServerSocket--that implement the client side of the connection and the server side of the connection, respectively

Java中的java.net包提供了Socket和ServerSocket類分別實現連線的客戶端和服務端。


Java中如何編寫?


伺服器端:

package com.dylan.socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 伺服器
 *
 * @author xusucheng
 * @create 2017-12-21
 **/
public class Server {
    public static final int PORT = 8858;//監聽的埠號

    public static void main(String[] args) throws Exception {
        System.out.println("Server started! Listening...");
        ServerSocket serverSocket = new ServerSocket(PORT);
        Socket server = serverSocket.accept();

        BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
        PrintWriter out = new PrintWriter(server.getOutputStream());

        String readLine = in.readLine();
        if (readLine != null) {
            System.out.println("Receive message from Client: " + readLine);
            out.println("Roger!");
        }

        out.close();
        in.close();
        server.close();
        serverSocket.close();


    }


}


客戶端:

package com.dylan.socket;

import java.io.*;
import java.net.Socket;

/**
 * 客戶端
 *
 * @author xusucheng
 * @create 2017-12-20
 **/
public class Client {
    public static final String HOST = "127.0.0.1";//伺服器地址
    public static final int PORT = 8858;//伺服器埠號

    public static void main(String[] args) throws Exception{
        Socket client = new Socket(HOST,PORT);
        //建立輸入流
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        //建立輸出流
        PrintWriter out = new PrintWriter(client.getOutputStream(),true);
        //向伺服器程式傳送資訊
        out.println("Hello Server! This is Client! ");
        //接收來自伺服器程式的響應
        String readLine=in.readLine();
        if(readLine!=null){
            System.out.println("Receive message from Server: "+readLine);
        }

        //關閉連結
        out.close();
        in.close();
        client.close();
    }
}

啟動

伺服器端

Server started! Listening...

Receive message from Client: Hello Server! This is Client!

客戶端:

Receive message from Server: Roger!









相關文章