Java套接字详解

Java套接字详解

参考文献

[1] https://docs.oracle.com/javase/tutorial/networking/sockets/index.html

正文开始

URL和URL连接提供了一个相对高级别的机制for accessing resources on the internet. 有的时候,你的程序需要一些相对低级别的网络通信,举个例子,当你想写一个client-server application的时候。

什么叫做URL连接? 什么叫做低级别的网络通信?
余成林:不用管

在客户端-服务器应用中,服务器提供了一些服务,例如

  • 处理数据库查询、
  • 发送当前股票的价格等。

客户端使用服务器提供的服务,例如

  • 客户端想要展现查询结果给用户,就需要服务器提供的数据库查询服务。

客户端和服务器之间的通信必须要是可靠的,即,没有数据被丢弃并且会按照次序到达客户端。

TCP提供了一个可靠的,端到端的通信渠道。因特网上的客户端-服务器应用利用这个渠道彼此进行通信。为了基于TCP进行通信,客户端程序和服务器程序彼此之间需要建立一个连接。每个程序将它的套接字绑定到连接的一端。当客户端和服务器要通信的时候,客户端和服务器就可以通过从建立的连接所绑定的套接字中读取和写入数据

什么是套接字?

一个套接字一个网络上两个应用程序之间建立的双向连接的一个端点。Socket 类被用来代表客户端和服务器程序之间的连接。java.net包提供了两个重要的类——Socket and ServerSocket。 Socket实现了连接的客户端一侧,ServerSocket实现了连接的服务器端一侧。

Normally, 服务器运行在一台电脑上,服务器有一个套接字,这个套接字和某个特定的端口绑定。这个服务器just waits, listening to the socket for a client to make a connection request.

在客户端一端: 客户端知道服务器运行的主机名和服务器正在listening的端口号。为了建立一个连接请求,客户端尝试和这个服务器约会。这个客户端也需要向服务器表明自己的身份,所以客户端也绑定了一个本地的端口号(这通常是由操作系统来帮我们完成甩我们操心了,我们只需要我们需要约会的对象的端口号和IP地址就好了)
在这里插入图片描述
如果一切顺利,服务器会accept这个连接,upon acceptance, the server gets a new socket bound to the same local port and has its remote endpoint set to the address and port of the client. 服务器必须要一个新的套接字,这样服务器才可以continue to listen to the origin socket for connection requests while tending to the needs of the connected client.
在这里插入图片描述
在客户端一侧,一旦连接被accept, 一个套接字就被成功创建,客户端就可以使用这个套接字和服务器进行通信。

现在客户端和服务器就可以通过writing to or reading from their sockets.

连接的端点是IP地址和端口号的结合。每个TCP connection can be uniquely identified by its two endpoints. 这样以来,你才可以在你的主机和服务器之间有多个连接。

java平台的java.net 包提供了一个类——Socket, 这个类implements one side of a two-way connection between your java program and another program on the network. Socket 类是平台无关的。

除此之外,java .net 还包含了ServerSocket类,which implements a socket that servers can use to listen for and accept connections to clients.

如果你想尝试连接Web, URL 类以及和URL相关的类可能比socket类更加适合。实际上,URLs are a relatively high-level connection to the Web and use sockets as part of the underlying implementation.

从套接字中读写

这一页包含了一个小例子,显示了客户端程序是怎么样从套接字中读写的。
让我们来看一个简单的例子,这个例子illustrates how a program can establish a connection to a server program using the Socket class and then, how the client can send data to and receive data from the server through the socket.

这个例子是实现了一个客户端, 这个客户单的服务器是一个echo server, The echo server receives data from its client and echoes it back.

EchoServer实现了一个echo server.

EchoClient实现的是客户端
EchoClient.java

import java.net.ServerSocket;
import java.net.Socket;
public class EchoClient {
    public static void main(String[] args) throws IOException {

        if (args.length != 2) {
            System.err.println(
                    "Usage: java EchoClient <host name> <port number>");
            System.exit(1);
        }

        String hostName = args[0];
        int portNumber = Integer.parseInt(args[1]);

        try (
                // 与服务器建立连接,获得客户端套接字
                Socket echoSocket = new Socket(hostName, portNumber);

                // 负责向套接字中写入,一次输入一行
                PrintWriter out =
                        new PrintWriter(echoSocket.getOutputStream(), true);

                // 负责从套接字中读入,一次读入一行
                BufferedReader in =
                        new BufferedReader(
                                new InputStreamReader(echoSocket.getInputStream()));

                // 负责从控制台读入,一次读入一行
                BufferedReader stdIn =
                        new BufferedReader(
                                new InputStreamReader(System.in))
        ) {
            String userInput;
            while ((userInput = stdIn.readLine()) != null) {
                out.println(userInput); // 写入套接字
                System.out.println("echo: " + in.readLine()); // 读取服务器返回的内容
            }
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host " + hostName);
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to " +
                    hostName);
            System.exit(1);
        }
    }
}

EchoServer.java

import java.net.*;
import java.io.*;
public class EchoServer {
    public static void main(String[] args) throws IOException {

        if (args.length != 1) {
            System.err.println("Usage: java EchoServer <port number>");
            System.exit(1);
        }

        int portNumber = Integer.parseInt(args[0]);

        try (
                // 创建Welcoming socket,并绑定端口号
                ServerSocket serverSocket =
                        new ServerSocket(Integer.parseInt(args[0]));

                // 建立专门的和该客户端连接的套接字,看到了吗!accept!
                Socket clientSocket = serverSocket.accept();

                // 负责向套接字中写入
                PrintWriter out =
                        new PrintWriter(clientSocket.getOutputStream(), true);

                // 负责读取套接字
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(clientSocket.getInputStream()));
        ) {
            String inputLine;
            // 从套接字中读取
            while ((inputLine = in.readLine()) != null) {
                System.out.println(inputLine);
                // 将从套接字中读取的写入到套接字中,这样客户端就可以收到了,我修改一下,改成upper
                out.println(inputLine.toUpperCase());
            }
        } catch (IOException e) {
            System.out.println("Exception caught when trying to listen on port "
                    + portNumber + " or listening for a connection");
            System.out.println(e.getMessage());
        }
    }
}

先运行服务器程序,后运行客户端程序!
如果对java输入流和输出流看不懂的话,请参见
Java输入流和输出流详解

其实,难就难在把Java代码和理论集合起来,我们需要搞清楚java套接字中每个方法的返回值是什么!

Writing a Client/Server Pair

上一页showed an example of how to write a client program that interacts with an existing server via a Socket object. 这一页将show you 怎么样写一个程序实现连接的另一端——服务器程序

Start!
真的是光阴似箭,已经晚上八点半了!加油
这一节讲解的还是非常不错的,加油!

这一节将教会你如何写一个Web服务器和客户端. The server in the client/server pair serves up Knock Knock jokes. Knock Knock jokes are favored by children and are usually vehicles for bad puns. They go like this:

先写到这儿吧,以后再说。具体参考链接:
https://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值