Я использую сервер, который выполняет следующие действия:
Принимая HELLO REQUEST от клиента, сервер немедленно отправляет ответ Hello
Послечтобы получить запрос STATUS, отправка ответа STATUS
Все работает нормально.После того, как я пытаюсь записать байты в сокет для команды, он прекращает чтение данных из клиента после выполнения команды, и мне приходится закрывать сокет, а затем снова начинать принимать.Что я могу делать не так?Код выглядит следующим образом:
PS. Впервые пишу код на Java
package main;
import main.cmd.ByteUtils;
import main.cmd.ReadPayload;
import main.datagram.EventFrame;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.Queue;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
public class Main {
private boolean run_new = true;
private boolean run_new_xxx = true;
private static Queue<byte[]> waitingQueue = new LinkedList<>();
byte[] HELLO_RESPONSE = {0, 05, 2, 1, 4, 0,(byte)0x0a};
byte[] STATUS_REPSONSE = {0, 2, 18, 1};
private String ip_address = "192.168.1.24";
ServerSocket serverSocket = null, keyServerSocket = null;
Socket clientSocket = null;
public Main() throws IOException {
}
public void doRun() throws IOException {
while(true)
{
if(run_new_xxx)
{
new Thread(){
public void run(){
try {
RunxxxkeyServer();
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
run_new_xxx = false;
if(run_new){
new Thread(){
public void run(){
try {
RunHubServer();
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
run_new = false;
}
}
public void RunxxxkeyServer()
{
try{
keyServerSocket = new ServerSocket(9998, 100, InetAddress.getByName(ip_address));
while (true) {
System.out.println("Waiting for a connection...");
final Socket activeSocket = keyServerSocket.accept();
System.out.println("Received a connection from " + activeSocket);
Runnable runnable = () -> handleClientRequest(activeSocket);
new Thread(runnable).start(); // start a new thread
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void handleClientRequest(Socket socket) {
try{
BufferedReader socketReader = null;
BufferedWriter socketWriter = null;
socketReader = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
socketWriter = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream()));
String inMsg = null;
while ((inMsg = socketReader.readLine()) != null) {
System.out.println("Received from client: " + inMsg);
if(inMsg.contains("xxx"))
{
String[] arr_request = inMsg.split(":");
System.out.println("Connected Client : "+inMsg);
waitingQueue.add(getDoorOpenCommand(arr_request[2]));
}
String outMsg = inMsg;
System.out.println(outMsg);
socketWriter.write(outMsg);
socketWriter.write("\n");
socketWriter.flush();
}
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
public void RunHubServer() throws IOException
{
try {
SetServer(InetAddress.getByName(ip_address), 9999, "abc.jks", "defj.jks", "changeit");
} catch (Exception e) {
System.err.println("Could not listen at 9999:"+ip_address);
e.printStackTrace();
System.exit(1);
}
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
boolean connected = true;
while (connected)
{
if(!clientSocket.isClosed() )
{
if(!waitingQueue.isEmpty()){
byte[] bytes = waitingQueue.remove();
send(bytes);
System.out.println("-> Sent DOOR_OPEN_COMMAND");
}
}
else {
clientSocket = serverSocket.accept();
}
try {
byte[] data = read();
if(data[0]==-1){
clientSocket.close();
}
else {
if (data.length >0 )
{
ReadPayload readPayload = ReadPayload.create(data);
EventFrame eventFrame = new EventFrame(readPayload);
System.out.println("<- " + readPayload.toHex() + " " + eventFrame.getPduId());
switch (eventFrame.getPduId()) {
case HELLO_REQUEST:
send(HELLO_RESPONSE);
System.out.println("-> " + ByteUtils.toHex(HELLO_RESPONSE) + "HELLO_RESPONSE" );
break;
case STATUS_REQUEST:
send(STATUS_REPSONSE);
System.out.println("-> " + ByteUtils.toHex(STATUS_REPSONSE) + "STATUS_RESPONSE" );
break;
case DOOR_OPPENING_RESULT:
System.out.println("<- " + eventFrame.getReadPayload().toString() + " ");
// connected = false;
break;
}
//connected = false;
}
}
}
catch(java.net.SocketTimeoutException e)
{
System.out.println("Timed out trying to read from socket");
}
catch(Exception e)
{
System.out.println("Timed out trying to read from socket");
}
}
clientSocket.close();
serverSocket.close();
run_new = true;
}
byte[] read() throws IOException {
byte[] readRaw = new byte[4096];
int readLengt = clientSocket.getInputStream().read(readRaw);
if (readLengt == -1) {
return new byte[]{-1};
}
byte[] returnBytes = new byte[readLengt];
System.arraycopy(readRaw, 0, returnBytes, 0, readLengt);
return returnBytes;
}
void send(byte[] bytes) {
try {
clientSocket.getOutputStream().write(bytes);
} catch (Exception e) {
e.printStackTrace();
}
}
public byte[] getDoorOpenCommand(String mac_address)
{
//0A9928
byte[] txBuffer = new byte[13];
char[] mac_in_array = mac_address.toCharArray();
String device_id = "";
int start = 4;
for (char c : mac_in_array)
{
int ascii = (int) c;
txBuffer[start] = (byte)ascii;
start++;
}
System.out.println(device_id);
txBuffer[0] = 0;
txBuffer[1] = 0X0C;
txBuffer[2] = 0X0C;
txBuffer[3] = 06;
txBuffer[10] = (byte)0XFF;
txBuffer[11] = (byte)0XFF;
txBuffer[12] = 00;
return txBuffer;
}
public void SetServer(InetAddress serverIpAddress, int port, String certFileName, String trustStorePassword, String keyPassword) throws IOException {
System.out.println("Setting up Hub secure TLS connection on " + serverIpAddress + ":" + port);
System.setProperty("javax.net.ssl.trustStore", certFileName);
System.setProperty("javax.net.ssl.trustStorePassword", keyPassword);
System.setProperty("javax.net.ssl.keyStore", trustStorePassword);
System.setProperty("javax.net.ssl.keyStorePassword", keyPassword);
System.setProperty("https.cipherSuites", "TLS_RSA_WITH_AES_256_CBC_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA");
serverSocket = SSLServerSocketFactory.getDefault().createServerSocket(port, 1, serverIpAddress);
}
public void SetServer(InetAddress serverIpAddress, int port) throws IOException {
System.out.println("Setting up connection on " + serverIpAddress + ":" + port);
serverSocket = ServerSocketFactory.getDefault().createServerSocket(port, 1, serverIpAddress);
}
}
.