做了一个指纹门锁,需要用TCP长连接进行服务端和门锁间的数据通信。
目前JAVA写socket服务端,门锁连接JAVA服务端。
服务端开了一个线程在监听门锁发来的数据(此处必须实时监听数据)
在监听的同时,若用socket发送数据的话,会出现异常报错。
第一个类负责接收socket连接
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import com.lock.util.StaticResource;
/**
* 侦听类
* 不断侦听Socket连接,将连接的Socket记录,并开启线程接受传来的数据
* @author plzwb
*/
public class ListenSocket implements Runnable{
ServerSocket serverSocket = null;
@Override
public void run() {
try {
serverSocket = new ServerSocket(2333);
} catch (IOException e) {
e.printStackTrace();
System.out.println("2333端口被占用");
}
while (true) {
try {
Socket socket = serverSocket.accept();
StaticResource.socketList.add(socket);
new Thread(new OpenRecordSocket(socket)).start();
System.out.println("Socket已连接");
} catch (IOException e) {
e.printStackTrace();
System.out.println("accept异常");
}
}
}
}
第二个类负责不断侦听数据
import java.io.IOException;
import java.net.Socket;
import com.lock.util.SocketUtil;
import com.lock.util.StaticResource;
public class OpenRecordSocket implements Runnable{
Socket socket = null;
SocketUtil socketUtil = null;
boolean state = true;
public OpenRecordSocket(Socket socket) {
this.socket = socket;
socketUtil = new SocketUtil(socket);
}
@Override
public void run() {
while(state){
try {
System.out.println("准备接受");
String text = socketUtil.receiveData();
System.out.println(text);
} catch (IOException e) {
StaticResource.socketList.remove(socket);
state = false;
System.out.println("Socket已经删除");
}
}
}
}
相关分类