Java makes requests to the network through 'sockets'
This article mainly introduces the relevant information about Java implementing TCP server through Socket. Friends who need it can refer to it
1 Introduction to Java Socket
The so-called socket is usually Also called "socket", it is used to describe an IP address and port, and is a handle to a communication chain. Applications usually make requests to the network or respond to network requests through "sockets". Socket and ServerSocket class libraries are located in the Java.NET package. ServerSocket is used on the server side, and Socket is used when establishing a network connection. When the connection is successful, both ends of the application will generate a Socket instance, operate this instance, and complete the required session. For a network connection, sockets are equal, there is no difference, there is no different level because of whether they are on the server side or on the client side.
2 TCPServer code example
import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * TCP服务器端,单例模式 * @author xiang * */ public class TCPServer implements Runnable { private static final Logger logger = LoggerFactory.getLogger(TCPServer.class); //成员变量/ private static TCPServer serverInstance; private static Map<String, SocketThread> socketMaps = new HashMap<String,SocketThread>(); //每个客户端连接时都会新建一个SocketThread与之对应 private static ServerSocket serverSocket; //服务器套接字 private static int serPort = 9999; //服务器端口号 private static boolean flag; //服务器状态标志 private static final int BUFFER_SIZE = 512; //数据接收字符数组大小 //构造函数/ private TCPServer() { } /** * 获取实例 * @return TCPServer实例serverInstance */ public static TCPServer getServerInstance(){ if(serverInstance==null) serverInstance = new TCPServer(); return serverInstance; } /** * 开启服务器 * @throws IOException */ public void openTCPServer() throws IOException{ if(serverSocket==null || serverSocket.isClosed()){ serverSocket = new ServerSocket(serPort); flag = true; } } /** * 关闭服务器 * @throws IOException */ public void closeTCPServer() throws IOException{ flag = false; if(serverSocket!=null) serverSocket.close(); /*for (Map.Entry<String, SocketThread> entry : socketMaps.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } */ for (SocketThread value : socketMaps.values()) value.closeConnect(); socketMaps.clear(); } /** * 服务器向客户端发送数据 * @param bytes[]:待发送的字符数组 * @param key 客户端的key,为空或""时表示数据群发 * @throws IOException */ public void sendMessage(String key,byte[] msgBytes){ if(key==null||key.equals("")){ for (SocketThread value : socketMaps.values()) value.sendMassage(msgBytes); }else{ SocketThread thread = socketMaps.get(key); if(thread!=null) thread.sendMassage(msgBytes); } } /** * 服务器向客户端发送数据 * @param key 客户端的key,为空或""时表示数据群发 * @param msgStr:待发送的字符串 * @throws IOException */ public void sendMessage(String key,String msgStr){ byte[] sendByte = msgStr.getBytes(); if(key==null||key.equals("")){ for (SocketThread value : socketMaps.values()) value.sendMassage(sendByte); }else{ SocketThread thread = socketMaps.get(key); if(thread!=null) thread.sendMassage(sendByte); } } @Override public void run() { logger.info("服务器线程已经启动"); while(true){ try { while(flag){ logger.info("服务器线程在监听状态中"); Socket socket = serverSocket.accept(); String key = socket.getRemoteSocketAddress().toString(); SocketThread thread = new SocketThread(socket,key); thread.start(); socketMaps.put(key, thread); logger.info("有客户端连接:"+key); } } catch (Exception e) { e.printStackTrace(); } } } /** * 处理连接后的数据接收请求内部类 * @author xiang * */ private class SocketThread extends Thread{ private Socket socket; private String key; private OutputStream out; private InputStream in; //构造函数 public SocketThread(Socket socket,String key) { this.socket = socket; this.key = key; } /** * 发送数据 * @param bytes * @throws IOException */ public void sendMassage(byte[] bytes){ try { if(out==null) out = socket.getOutputStream(); out.write(bytes); } catch (Exception e) { e.printStackTrace(); try { closeConnect(); } catch (IOException e1) { e1.printStackTrace(); } socketMaps.remove(key); } } /** * 关闭连接,释放资源 * @throws IOException */ public void closeConnect() throws IOException{ if(out!=null) out.close(); if(in!=null) in.close(); if(socket!=null && socket.isConnected()) socket.close(); } @Override public void run() { byte[] receivBuf = new byte[BUFFER_SIZE]; int recvMsgSize; try { in = socket.getInputStream(); out = socket.getOutputStream(); while ((recvMsgSize = in.read(receivBuf)) != -1) { String receivedData = new String(receivBuf, 0, recvMsgSize); System.out.println("Reverve form[port" + socket.getPort() + "]:" + receivedData); System.out.println("Now the size of socketMaps is" + socketMaps.size()); /************************************************************** * * 接收数据后的处理过程 * **************************************************************/ } // response to client byte[] sendByte = "The Server has received".getBytes(); // out.write(sendByte, 0, sendByte.length); out.write(sendByte); System.out.println("To Cliect[port:" + socket.getPort() + "] 回复客户端的消息发送成功"); closeConnect(); socketMaps.remove(key); } catch (Exception e) { e.printStackTrace(); try { closeConnect(); } catch (IOException e1) { e1.printStackTrace(); } } } ////////////// public int getport(){ return socket.getPort(); } } //. end SocketThread }
[Related recommendations]
1. Special recommendations: "php Programmer Toolbox" V0.1 version download
3. Comprehensive analysis of Java annotation
The above is the detailed content of Java makes requests to the network through 'sockets'. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo
