A lot of times in the Javaweb project we need to use socket communication to achieve functionality, the use of sockets in the web we need to establish a listener, when the program is started, the socket listening. Our scenario is in a Java project that needs to be external such as a hardware device, through TCP communication, get the data from the device, and respond to the data.
Take a look at the web's listening 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)
{
//New Thread class
socketthread=new socketthread (null);
Start thread
socketthread.start ();}}
To create a 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");
The catch (Exception e) {System.out.println ("Socketthread Create socket Service error");
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 ("Socketthread Create socket Service error");
E.printstacktrace (); }} public void Closesocketserver () {try {if (Null!=serversocket &&!serversocket.isclosed ()) {SERVERSOCKet.close ();
The 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;
The input stream for the socket processed by the 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 {///loops through the socket to read the data sent by the client while (true) {content = Readfromclient ();
SYSTEM.OUT.PRINTLN (content);
if (content = = null) {break;
} outputstream OS = Socket.getoutputstream ();
Os.write ("RES, ok,<, Xiaoming,,, #" + "\ n"). GetBytes ("utf-"));
Os.flush ();
} catch (IOException e) {e.printstacktrace ();
}//define methods to read client data private String readfromclient () {try {str = br.readline ();
return str; }
If an exception is caught, the client that corresponds to the socket has closed catch (IOException e) {try {br.close (); Reader.close (); Socket.close ();} catch (Ioexc
Eption 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 {
Socke T 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 cycle
os.close ();///close socket output stream
is.close ();//close socket input stream
socket.close ();//close socket
}
}
The above is a small series to introduce the Java Web project in the use of socket communication multithreading, long connection method, I hope to help!