Home Java javaTutorial Methods of using Socket communication for multi-threading and long connections in Java Web projects

Methods of using Socket communication for multi-threading and long connections in Java Web projects

Jan 05, 2017 pm 02:18 PM

Many times in javaweb projects we need to use Socket communication to implement functions. To use Socket in the web, we need to create a listening program. When the program starts, start the socket listening. Our application scenario is in a Java project, where we need to connect an external hardware device, communicate through TCP, obtain the data transmitted by the device, and respond to the data.

Let’s take a look at the web monitoring code first:

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class AttendSocetListener implements ServletContextListener{
private SocketThread socketThread;
public void contextDestroyed(ServletContextEvent arg) { 
if(null!=socketThread && !socketThread.isInterrupted()) 
{ 
socketThread.closeSocketServer(); 
socketThread.interrupt(); 
} 
} 
@Override
public void contextInitialized(ServletContextEvent arg) { 
// TODO Auto-generated method stub 
if(null==socketThread) 
{ 
//新建线程类 
socketThread=new SocketThread(null); 
//启动线程 
socketThread.start(); 
} 
} 
}
Copy after login

Create thread:

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class SocketThread extends Thread
{
private ServerSocket serverSocket = null; 
public SocketThread(ServerSocket serverScoket){ 
try { 
if(null == serverSocket){ 
this.serverSocket = new ServerSocket(); 
System.out.println("socket start"); 
} 
} catch (Exception e) { 
System.out.println("SocketThread创建socket服务出错"); 
e.printStackTrace(); 
} 
} 
public void run(){ 
while(true){ 
try { 
if(serverSocket==null){
break;
}else if(serverSocket.isClosed()){
break;
}
Socket socket = serverSocket.accept(); 
if(null != socket && !socket.isClosed()){ 
//处理接受的数据 
Thread t = new Thread(new SocketOperate(socket)); 
t.start(); 
}else{
break;
}
}catch (Exception e) { 
System.out.println("SocketThread创建socket服务出错"); 
e.printStackTrace(); 
} 
} 
} 
public void closeSocketServer(){ 
try { 
if(null!=serverSocket && !serverSocket.isClosed()) 
{ 
serverSocket.close(); 
} 
} catch (IOException e) { 
// TODO Auto-generated catch block 
e.printStackTrace(); 
} 
} 
}
Copy after login

Process the received data:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class SocketOperate implements Runnable { 
private Socket socket; 
//该线程所处理的Socket所对应的输入流 
BufferedReader br = null; 
String str = null; 
String content = null; 
InputStreamReader reader=null; 
public SocketOperate(Socket socket) throws IOException 
{ 
this.socket = socket; 
reader = new InputStreamReader(this.socket.getInputStream(),"utf-"); 
br = new BufferedReader(reader); 
} 
@Override
public void run() 
{ 
try
{ 
// 采用循环不断从Socket中读取客户端发送过来的数据 
while (true) 
{ 
content = readFromClient(); 
System.out.println(content);
if (content == null) 
{ 
break; 
} 
OutputStream os = socket.getOutputStream(); 
os.write(("RES, OK,<年班,小明>, ,#" + "\n").getBytes("utf-")); 
os.flush();
} 
} 
catch (IOException e) 
{ 
e.printStackTrace(); 
} 
} 
//定义读取客户端数据的方法 
private String readFromClient() 
{ 
try
{ 
str = br.readLine(); 
return str; 
} 
//如果捕捉到异常,表明该Socket对应的客户端已经关闭 
catch (IOException e) 
{ 
try {
br.close();
reader.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 
} 
return null; 
} 
}
Copy after login

Client code:

package
import java.io.*;
import java.net.*;
public class TalkClient {
public static void main(String args[]) throws UnknownHostException, IOException {
Socket socket=new Socket("...",);
PrintWriter os=new PrintWriter(socket.getOutputStream());
BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
int i=;
while(socket.isConnected()){
os.print("BEAT,,,,.,,#"+"\n");
os.flush();
System.out.println("Client:"+i);
System.out.println("Server:"+is.readLine());
i++;
} 
//继续循环
os.close(); //关闭Socket输出流
is.close(); //关闭Socket输入流
socket.close(); //关闭Socket
}
}
Copy after login

For more related articles on using Socket communication multi-threading and long connection methods in Java Web projects, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles