在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
Java网络教程 - Java TCP服务器
我们可以使用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()方法调用阻塞执行,直到来自远程客户端的请求到达其等待队列。
Socket activeSocket = serverSocket.accept(); Socket类包含两个方法 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(); } } } |
请发表评论