gpt4 book ai didi

java - 我无法在我的 java 套接字程序中将多个传感器连接到服务器

转载 作者:太空宇宙 更新时间:2023-11-04 10:33:41 25 4
gpt4 key购买 nike

我已经使用套接字实现了服务器和客户端。多个客户端必须能够连接。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Set;

import sensors.FireAlarmSensor;

public class SensorServer {
private static final int port = 9000;
private static HashMap<String, PrintWriter> fireSensorPrintersList = new HashMap<String, PrintWriter>();
private static HashMap<String,FireAlarmSensor> fireSensorsList = new HashMap<String,FireAlarmSensor>();

private static String sensorIDNumber;
private static double temperatureLevel;
private static double CO2Level;
private static double batteryLevel;
private static double smokeLevel;

public static void main(String args[]){
System.out.println("Sensor Server Is Running");
ServerSocket clientListener = null;
try {
clientListener = new ServerSocket(port);
new sensorHandler(clientListener.accept()).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
clientListener.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

public static class sensorHandler extends Thread{
private String sensorID;
private Socket socket;
private BufferedReader receiver;
private PrintWriter sender;

public sensorHandler(Socket socket) {
this.socket = socket;
try {
this.receiver = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.sender = new PrintWriter(socket.getOutputStream(),true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

@Override
public void run(){
while(true){
sender.println("REQUESTID");
try {
sensorID = receiver.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

if(sensorID == null){
System.out.println("Empty Sensor ID");
}

synchronized (fireSensorPrintersList) {
if(!fireSensorPrintersList.containsKey(sensorID)){
fireSensorPrintersList.put(sensorID,sender);
break;
}
}
}

sender.println("SENSORACCEPTED");
try{
while(true){
//Set<String> sensorIDList= fireSensorPrintersList.keySet();
/*for(PrintWriter writer:fireSensorPrintersList.values()){
sensorIDNumber = fireSensorsList.get(sensorIDList).getSensorID();
temperatureLevel = fireSensorsList.get(sensorIDList).getTemperatureLevel();
batteryLevel = fireSensorsList.get(sensorIDList).getBatteryLevel();
CO2Level = fireSensorsList.get(sensorIDList).getCO2Level();
smokeLevel = fireSensorsList.get(sensorIDList).getSmokeLevel();
}*/

/*try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
}
finally {
try {
socket.close();
System.out.println("Sensor server closed");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}

这是客户端(传感器)的代码。

package sensors;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Serializable;
import java.net.Socket;
import java.util.Scanner;

public class FireAlarmSensor implements Serializable{
BufferedReader lineIn;
PrintWriter lineOut;

private String sensorID = "Not Set";
private BatterySensor batterySensor;
private TemperatureSensor temperatureSensor;
private SmokeSensor smokeSensor;
private CO2Sensor co2Sensor;

public FireAlarmSensor(String sensorID){
this.sensorID = sensorID;
this.batterySensor = new BatterySensor();
this.temperatureSensor = new TemperatureSensor();
this.smokeSensor = new SmokeSensor();
this.co2Sensor = new CO2Sensor();
}

public FireAlarmSensor(){
/*JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);*/
}

public String getSensorID(){
return this.sensorID;
}

public double getBatteryLevel(){
return batterySensor.getSensorData();
}

public double getTemperatureLevel(){
return temperatureSensor.getSensorData();
}

public double getSmokeLevel(){
return smokeSensor.getSensorData();
}

public double getCO2Level(){
return co2Sensor.getSensorData();
}

public void run(){
String serverAddress = "localhost";
Socket socket = null;

try {
socket = new Socket(serverAddress,9000);
lineIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
lineOut = new PrintWriter(socket.getOutputStream(),true);

while(true){
String serverInput = lineIn.readLine();
if(serverInput.startsWith("REQUESTID")){
Scanner userInput = new Scanner(System.in);
System.out.print("Enter the Sensor ID : ");
String sensorID = userInput.nextLine();
lineOut.println(sensorID);
}
else if(serverInput.startsWith("SENSORACCEPTED")){
System.out.println("Sensor Is Accepted");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*finally{
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
}

public static void main(String args[]){
FireAlarmSensor sensor = new FireAlarmSensor();
sensor.run();
}
}

服务器在我的程序中运行得非常好。它不会随时崩溃,第一个传感器也可以与服务器连接,并且它也永远不会崩溃。但是,当尝试通过运行 FireAlarmSensor.class 文件将另一个传感器连接到服务器时,第二个传感器出现以下异常并崩溃。

java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at sensors.FireAlarmSensor.run(FireAlarmSensor.java:64)
at sensors.FireAlarmSensor.main(FireAlarmSensor.java:96)

我正在使用 eclipse neon 在同一台机器上运行服务器和所有传感器。

Client(Sensor)中的第16到27行会导致错误,因为我还没有上传该java文件。请在运行时注释或删除它们。

最佳答案

main 方法仅调用 accept 一次,因此只有一个客户端可以连接也就不足为奇了。尝试循环接受客户端:

private static boolean shouldExit = false;

public static void main(String args[]) {
System.out.println("Sensor Server Is Running");

try (ServerSocket listener = new ServerSocket(port)) {
acceptLoop(listener);
} catch (IOException e) {
e.printStackTrace();
}
}

private static void acceptLoop(ServerSocket listener) throws IOException {
while (!shouldExit) {
// accept() blocks until a connection is made
Socket client = listener.accept();
new sensorHandler(client).start();
}
}

这将永远循环,接受新客户端,直到您将 shouldExit 设置为 true。即主线程。

我冒昧地使用了 Java 7 try-with-resources语句(try (ServerSocket Listener = ...))。它本质上做了你复杂的 try-catch-finally 所做的事情 - 自动关闭 ServerSocket。

关于java - 我无法在我的 java 套接字程序中将多个传感器连接到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49725227/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com