[size=13.63636302948px]
[size=13.63636302948px]7、TCP服务器端
[size=13.63636302948px] 在Socket编程中,服务器端远比客户端要复杂得多。服务器端的工作就是建立一个通信终端,被动的等待客户端的连接。下面这个服务器端程序的示例的作用是:监听从控制台输入获取的端口号,并且将客户端发送过来的消息,再发送回去。
[size=13.63636302948px] 代码如下:
[size=13.63636302948px]import java.io.IOException;
[size=13.63636302948px]import java.io.InputStream;
[size=13.63636302948px]import java.io.OutputStream;
[size=13.63636302948px]import java.net.ServerSocket;
[size=13.63636302948px]import java.net.Socket;
[size=13.63636302948px]import java.net.SocketAddress;
[size=13.63636302948px]import java.text.MessageFormat;
[size=13.63636302948px]public class TCPEchoServer {
[size=13.63636302948px] private static final int BUFSIZE = 32;
[size=13.63636302948px] public static void main(String[] args) throws IOException {
[size=13.63636302948px] // 从控制台获取需要监听的端口号
[size=13.63636302948px] if (args.length != 1)
[size=13.63636302948px] throw new IllegalArgumentException("Parameter(s):<Port>");
[size=13.63636302948px] // 获取端口号
[size=13.63636302948px] int servPort = Integer.parseInt(args[0]);
[size=13.63636302948px] // 实例化一个ServerSocket对象实例
[size=13.63636302948px] ServerSocket servSocket = new ServerSocket(servPort);
[size=13.63636302948px] System.out.println(MessageFormat.format("开始启动监听,端口号:{0}", args[0]));
[size=13.63636302948px] // 初始接收数据的总字节数
[size=13.63636302948px] int recvMsgSize;
[size=13.63636302948px] // 接收数据的缓冲区
[size=13.63636302948px] byte[] receiveBuf = new byte[BUFSIZE];
[size=13.63636302948px] // 循环迭代,监听端口号,处理新的连接请求
[size=13.63636302948px] while (true) {
[size=13.63636302948px] // 阻塞等待,每接收到一个请求就创建一个新的连接实例
[size=13.63636302948px] Socket clntSocket = servSocket.accept();
[size=13.63636302948px] // 获取连接的客户端的SocketAddress
[size=13.63636302948px] SocketAddress AddressclientAddress = clntSocket.getRemoteSocketAddress();
[size=13.63636302948px] // 打印输出连接客户端地址信息
[size=13.63636302948px] System.out.println("Handlingclientat" + AddressclientAddress);
[size=13.63636302948px] // 从客户端接收数据的对象
[size=13.63636302948px] InputStream in = clntSocket.getInputStream();
[size=13.63636302948px] // 向客户端发送数据的对象
[size=13.63636302948px] OutputStream out = clntSocket.getOutputStream();
[size=13.63636302948px] // 读取客户端发送的数据后,再发送到客户端
[size=13.63636302948px] while ((recvMsgSize = in.read(receiveBuf)) != -1) {
[size=13.63636302948px] out.write(receiveBuf, 0, recvMsgSize);
[size=13.63636302948px] }
[size=13.63636302948px] // 客户端关闭连接时,关闭连接
[size=13.63636302948px] System.out.println("客户端关闭连接");
[size=13.63636302948px] clntSocket.close();
[size=13.63636302948px] }
[size=13.63636302948px] }
[size=13.63636302948px]}