Many times in javaweb projects, we need to use Socket communication to implement functions. When using Socket in the web, we need to establish a listener program, and start socket listening when the program starts. Our application scenario is in a Java project, which requires external hardware devices to communicate through tcp to obtain data uploaded by the device and respond to the data.
Let's take a look at the web listening code:
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.isInterrupt()) { socketThread.closeSocketServer(); socketThread.interrupt(); } } @Override public void contextInitialized(ServletContextEvent arg) { // TODO Auto-generated method stub if(null==socketThread) { // Create new thread class socketThread=new SocketThread(null); // Start thread socketThread.start(); } } }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 error creating socket service"); 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()){ // Process accepted data Thread t = new Thread(new SocketOperate(socket)); t.start(); }else{break;}}catch (Exception e) { System.out.println("Error creating socket service in SocketThread"); e.printStackTrace(); } } } public void closeSocketServer(){ try { if(null!=serverSocket && !serverSocket.isClosed()) { serverSocket.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }Processing 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; //Input stream corresponding to Socket processed by this thread 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 { // Use a loop to continuously read the data sent by the client from the Socket while (true) { content = readFromClient(); System.out.println(content); if (content == null) { break; } OutputStream os = socket.getOutputStream(); os.write(("RES, OK,<Year Class, Xiao Ming>, ,#" + "/n").getBytes("utf-")); os.flush();} } catch (IOException e) { e.printStackTrace(); } } //Define the method to read client data private String readFromClient() { try { str = br.readLine(); return str; } //If an exception is caught, it means that the client corresponding to the socket has closed the catch (IOException e) { try {br.close();reader.close();socket.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} } return null; } }Client code:
packageimport 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++;} //Continue looping os.close(); //Close Socket output stream is.close(); //Close Socket input stream socket.close(); //Close Socket}}The above is the method of using Socket communication multi-threaded and long connections in Java Web projects introduced by the editor. I hope it will be helpful to everyone!