服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - JAVA教程 - Java Web项目中使用Socket通信多线程、长连接的方法

Java Web项目中使用Socket通信多线程、长连接的方法

2020-04-21 11:45程序员 JAVA教程

很多时候在javaweb项目中我们需要用到Socket通信来实现功能,在web中使用Socket我们需要建立一个监听程序,在程序启动时,启动socket监听。接下来通过本文给大家介绍Java Web项目中使用Socket通信多线程、长连接的方法,感兴趣的朋友

很多时候在javaweb项目中我们需要用到Socket通信来实现功能,在web中使用Socket我们需要建立一个监听程序,在程序启动时,启动socket监听。我们的应用场景是在java项目中,需要外接如一个硬件设备,通过tcp通信,获取设备传上来的数据,并对数据做回应。

先看一下web的监听代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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();
}
}
}

创建线程:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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();
}
}
}

处理接受到的数据:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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;
}
}

客户端代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
}
}

以上所述是小编给大家介绍的Java Web项目中使用Socket通信多线程、长连接的方法,希望对大家有所帮助!

延伸 · 阅读

精彩推荐