


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(); } } }
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(); } } }
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; } }
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 } }
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!

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.


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

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

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools
