阅读(4290)
赞(0)
Java TCP服务器
2017-01-09 19:20:15 更新
Java网络教程 - Java TCP服务器
ServerSocket
类的一个对象表示Java中的TCP服务器套接字。
ServerSocket
对象可以接受来自远程客户端的连接请求。
我们可以使用no-args构造函数创建一个未绑定的服务器套接字,并使用其bind()方法将其绑定到本地端口和本地IP地址。
例子
以下代码显示如何创建服务器套接字:
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
您可以通过使用以下任何构造函数在一个步骤中组合create,bind和listen操作。
等待队列大小的默认值为50。
本地IP地址的缺省值是通配符地址,即服务器计算机的所有IP地址。
ServerSocket(int port) ServerSocket(int port, int waitQueueSize) ServerSocket(int port, int waitQueueSize, InetAddress bindAddr)
您可以将套接字创建和绑定步骤合并为一个语句。
以下代码显示如何在端口12900创建服务器套接字,其中100作为等待队列大小,并在localhost回送地址。
ServerSocket serverSocket = new ServerSocket(12900, 100, InetAddress.getByName("localhost"));
要接受远程连接请求,请调用服务器套接字上的 accept()
方法。
accept()方法调用阻塞执行,直到来自远程客户端的请求到达其等待队列。
The following code calls on ServerSocket will wait for a new remote connection request.
Socket activeSocket = serverSocket.accept();
Socket类包含两个方法 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()方法关闭连接。关闭套接字还会关闭其输入和输出流。
activeSocket.close();
以下代码显示如何创建服务器套接字。
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(); } } }