欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【学习笔记】Java网络编程

程序员文章站 2022-07-11 23:49:57
...

Socket 编程

Socket是应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口。在设计模式中,Socket其实就是一个门面模式,它把复杂的TCP/IP协议族隐藏在Socket接口后面,对用户来说,一组简单的接口就是全部,让Socket去组织数据,以符合指定的协议。可以认为socket=IP+端口。

当连接建立时,服务器会创建一个 Socket 对象。客户端和服务器现在可以通过对 Socket 对象的写入和读取来进行通信。

服务器与客户端进行通信

  • 服务器实例化一个 ServerSocket 对象,表示通过服务器上的端口通信。
  • 服务器调用 ServerSocket 类的 accept() 方法,该方法将一直等待,直到客户端连接到服务器上给定的端口。
  • 服务器正在等待时,一个客户端实例化一个 Socket 对象,指定服务器名称和端口号来请求连接。
  • Socket 类的构造函数试图将客户端连接到指定的服务器和端口号。如果通信被建立,则在客户端创建一个 Socket 对象能够与服务器进行通信。
  • 在服务器端,accept() 方法返回服务器上一个新的 socket 引用,该 socket 连接到客户端的 socket。

服务器

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class Server extends Thread {
    private final ServerSocket serverSocket;

    public Server(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        serverSocket.setSoTimeout(10000);
    }

    public void start() {
        while (true) {
            try {
                System.out.println("Waiting for being Connected. Port is " + serverSocket.getLocalPort() + "...");
                Socket server = serverSocket.accept();
                System.out.println("Remote host address is " + server.getRemoteSocketAddress());
                DataInputStream in = new DataInputStream(server.getInputStream());
                System.out.println(in.readUTF());
                DataOutputStream out = new DataOutputStream(server.getOutputStream());
                out.writeUTF(server.getLocalSocketAddress() + " is connected successfully!");
                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 thread = new Server(port);
            thread.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

客户端

public class Client {
    public static void main(String args[]){
        String serverName = args[0];
        int port = Integer.parseInt(args[1]);
        try {
            System.out.println("Connect to the host " + serverName + ", the port is " + port);
            Socket client = new Socket(serverName, port);
            System.out.println("The remote host address is " + client.getRemoteSocketAddress());
            OutputStream outToServer = client.getOutputStream();
            DataOutputStream out = new DataOutputStream(outToServer);

            out.writeUTF("Get data from " + client.getLocalSocketAddress());
            InputStream inFromServer = client.getInputStream();
            DataInputStream in = new DataInputStream(inFromServer);
            System.out.println("The server response is " + in.readUTF());
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
/* 客户端输出
Connect to the host localhost, the port is 6066
The remote host address is localhost/127.0.0.1:6066
The server response is /127.0.0.1:6066 is connected successfully!
*/

/* 服务器输出
Waiting for being Connected. Port is 6066...
Remote host address is /127.0.0.1:63877
Get data from /127.0.0.1:63877
Waiting for being Connected. Port is 6066...
Socket timed out!
*/
相关标签: 学习记录