我正在做一个 web 项目,我有一个名为 Connection 的类,这个类通过 TCP/IP 与另一个设备建立连接,当有一个 http get 请求时,我实例化一个对象“connection_o”并启动一个线程来保持像这样通信:“connection_o.start”所以建立了连接,在下一个http请求中我必须发送一条消息,但是当我再次执行“doGet”以避免空指针异常时,我需要再次实例化对象,但我不能,因为我需要使用在运行之前使用的相同实例,在我的测试中,连接继续工作,但我无法访问我已经创建的线程。所以我需要某种静态类或一种方法来使用已经运行的线程。
这是套接字的代码
import java.io.*;
import java.net.*;
public class Provider extends Thread{
ServerSocket providerSocket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Provider(){}
public void run()
{
try{
//1. creating a server socket
providerSocket = new ServerSocket(2004, 10);
//2. Wait for connection
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
//3. get Input and Output streams
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
sendMessage("Connection successful");
//4. The two parts communicate via the input and output streams
do{
try{
message = (String)in.readObject();
// System.out.println("client>" + message);
if (message.equals("cambio la variable"))
System.out.println("Abriendo Puerta");
// sendMessage("bye");
}
catch(ClassNotFoundException classnot){
System.err.println("Data received in unknown format");
}
}while(!message.equals("bye"));
}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
//4: Closing connection
try{
in.close();
out.close();
providerSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
public void sendMessage(String msg)
{
try{
out.writeObject(msg);
out.flush();
// System.out.println("server>" + msg);
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
这是 doGet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String s = request.getParameter("s");
//Routine to send blink to RPi
if (s.equals("Start")){
Provider c = new Provider();
c.Inicio();
}
if (s.equals("Send")){
c.sendMessage("Blink");
}
提前致谢