Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Java服务器,html客户端,无法向服务器发送消息_Javascript_Java_Server_Client - Fatal编程技术网

Javascript Java服务器,html客户端,无法向服务器发送消息

Javascript Java服务器,html客户端,无法向服务器发送消息,javascript,java,server,client,Javascript,Java,Server,Client,我的项目有点小问题。我有一个用Java编写的服务器和一些用html/js编写的客户端。连接以某种方式工作,但只要我想从客户端向服务器发送消息,它就会返回一个错误:Uncaught InvalidStateError:未能在“WebSocket”上执行“send”:仍处于连接状态 希望你们中的一些很棒的家伙可以查看我的代码并帮助我: 服务器代码: Server.java public class Server { static ArrayList<Clients> clientsAr

我的项目有点小问题。我有一个用Java编写的服务器和一些用html/js编写的客户端。连接以某种方式工作,但只要我想从客户端向服务器发送消息,它就会返回一个错误:Uncaught InvalidStateError:未能在“WebSocket”上执行“send”:仍处于连接状态

希望你们中的一些很棒的家伙可以查看我的代码并帮助我:

服务器代码:

Server.java

public class Server {

static ArrayList<Clients> clientsArrayList = new ArrayList<>();
private static int clientCount = 1;
private static int port;
private static ServerSocket ss;
private Socket socket;
private Clients clienthandler;
static boolean isRunning = true;

public Server(int port) throws IOException {

    this.port = port;
    setSs(new ServerSocket(port));
}

public void run() throws IOException {

    while (isRunning) {

        log("Listening on " + port + "...");
        socket = getSs().accept();
        log("Receiving client... " + socket);

        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));        
        PrintWriter out = new PrintWriter(socket.getOutputStream());

        String s;
        while ((s = in.readLine()) != null) {
            log(s);
            if (s.isEmpty()) {
                break;
            }
        }

        log("Creating a new handler for this client...");

        clienthandler = new Clients(socket, "Client " + clientCount, in, out);
        Thread t = new Thread(clienthandler);

        clientsArrayList.add(clienthandler);
        log("Added to client list");
        t.start();
        clientCount++;

        GUI.texttoclientlog();
    }

}

public static ServerSocket getSs() {
    return ss;
}

public static void setSs(ServerSocket ss) {
    Server.ss = ss;
}

public void log(String logtext) {
    System.out.println(logtext);
    GUI.texttolog(logtext);

}
public class Server {

static ArrayList<Clients> clientsArrayList = new ArrayList<>();
private static int clientCount = 1;
private static int port;
private static ServerSocket ss;
private Socket socket;
private Clients clienthandler;
static boolean isRunning = true;
private InputStream in;
private OutputStream out;

public Server(int port) throws IOException {

    Server.port = port;
    setSs(new ServerSocket(port));
}

public void run() throws IOException, NoSuchAlgorithmException {

    while (isRunning) {

        log("Listening on " + port + "...");
        socket = getSs().accept();
        log("Receiving client... " + socket);

        in = socket.getInputStream();
        out = socket.getOutputStream();


        @SuppressWarnings("resource")
        String data = new Scanner(in, "UTF-8").useDelimiter("\\r\\n\\r\\n").next();

        Matcher get = Pattern.compile("^GET").matcher(data);

        if (get.find()) {

            Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data);
            match.find();
            byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n" + "Connection: Upgrade\r\n"
                    + "Upgrade: websocket\r\n" + "Sec-WebSocket-Accept: "
                    + DatatypeConverter.printBase64Binary(MessageDigest.getInstance("SHA-1")
                            .digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes("UTF-8")))
                    + "\r\n\r\n").getBytes("UTF-8");

            out.write(response, 0, response.length);

            log("Creating a new handler for this client...");

            clienthandler = new Clients(socket, "Client " + clientCount, in, out);
            Thread t = new Thread(clienthandler);

            clientsArrayList.add(clienthandler);
            log("Added to client list");
            t.start();
            clientCount++;

            GUI.texttoclientlog();

        } else {

            log("Handshake failed");

        }

    }

}

public static ServerSocket getSs() {
    return ss;
}

public static void setSs(ServerSocket ss) {
    Server.ss = ss;
}

public void log(String logtext) {
    System.out.println(logtext);
    GUI.texttolog(logtext);

}
}

和JS客户端代码:

    <script>
  var connection;

  connection = new WebSocket("ws://localhost:6788/");
  console.log("connection established");

  connection.onmessage = function (e) { console.log(e.data); };
  connection.onopen = () => conn.send("Connection established");
  connection.onerror = function (error) {
    console.log("WebSocket Error" + error);
  };

  function Send() {
    if (connection.readyState === 1) {
      connection.send("test");
    }
        console.log("error sending");
    }

</script>

WebSocket会话是通过一个。 Post握手完成且连接升级后,服务器和客户端可以发送消息。是Java中的一个示例WebSocket服务器

将客户端运行方法更新为

public void run() {

    int len = 0;            
    byte[] b = new byte[80];
    while(true){
        try {
            len = in.read(b);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if(len!=-1){

            byte rLength = 0;
            int rMaskIndex = 2;
            int rDataStart = 0;
            //b[0] is always text in my case so no need to check;
            byte data = b[1];
            byte op = (byte) 127;
            rLength = (byte) (data & op);

            if(rLength==(byte)126) rMaskIndex=4;
            if(rLength==(byte)127) rMaskIndex=10;

            byte[] masks = new byte[4];

            int j=0;
            int i=0;
            for(i=rMaskIndex;i<(rMaskIndex+4);i++){
                masks[j] = b[i];
                j++;
            }

            rDataStart = rMaskIndex + 4;

            int messLen = len - rDataStart;

            byte[] message = new byte[messLen];

            for(i=rDataStart, j=0; i<len; i++, j++){
                message[j] = (byte) (b[i] ^ masks[j % 4]);
            }

            System.out.println(new String(message)); 

            b = new byte[80];

        }
    }
}
基于这样的回答


在我看来,您可以利用SpringWebSocket支持,而不是自己编写。我已经创建了一个同样使用ProtoBuf的应用程序,您也可以查看SpringWebSocket入门指南,这是更新后的代码。它从html客户端接收字节。但我不知道如何破译它们:

Server.java

public class Server {

static ArrayList<Clients> clientsArrayList = new ArrayList<>();
private static int clientCount = 1;
private static int port;
private static ServerSocket ss;
private Socket socket;
private Clients clienthandler;
static boolean isRunning = true;

public Server(int port) throws IOException {

    this.port = port;
    setSs(new ServerSocket(port));
}

public void run() throws IOException {

    while (isRunning) {

        log("Listening on " + port + "...");
        socket = getSs().accept();
        log("Receiving client... " + socket);

        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));        
        PrintWriter out = new PrintWriter(socket.getOutputStream());

        String s;
        while ((s = in.readLine()) != null) {
            log(s);
            if (s.isEmpty()) {
                break;
            }
        }

        log("Creating a new handler for this client...");

        clienthandler = new Clients(socket, "Client " + clientCount, in, out);
        Thread t = new Thread(clienthandler);

        clientsArrayList.add(clienthandler);
        log("Added to client list");
        t.start();
        clientCount++;

        GUI.texttoclientlog();
    }

}

public static ServerSocket getSs() {
    return ss;
}

public static void setSs(ServerSocket ss) {
    Server.ss = ss;
}

public void log(String logtext) {
    System.out.println(logtext);
    GUI.texttolog(logtext);

}
public class Server {

static ArrayList<Clients> clientsArrayList = new ArrayList<>();
private static int clientCount = 1;
private static int port;
private static ServerSocket ss;
private Socket socket;
private Clients clienthandler;
static boolean isRunning = true;
private InputStream in;
private OutputStream out;

public Server(int port) throws IOException {

    Server.port = port;
    setSs(new ServerSocket(port));
}

public void run() throws IOException, NoSuchAlgorithmException {

    while (isRunning) {

        log("Listening on " + port + "...");
        socket = getSs().accept();
        log("Receiving client... " + socket);

        in = socket.getInputStream();
        out = socket.getOutputStream();


        @SuppressWarnings("resource")
        String data = new Scanner(in, "UTF-8").useDelimiter("\\r\\n\\r\\n").next();

        Matcher get = Pattern.compile("^GET").matcher(data);

        if (get.find()) {

            Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data);
            match.find();
            byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n" + "Connection: Upgrade\r\n"
                    + "Upgrade: websocket\r\n" + "Sec-WebSocket-Accept: "
                    + DatatypeConverter.printBase64Binary(MessageDigest.getInstance("SHA-1")
                            .digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes("UTF-8")))
                    + "\r\n\r\n").getBytes("UTF-8");

            out.write(response, 0, response.length);

            log("Creating a new handler for this client...");

            clienthandler = new Clients(socket, "Client " + clientCount, in, out);
            Thread t = new Thread(clienthandler);

            clientsArrayList.add(clienthandler);
            log("Added to client list");
            t.start();
            clientCount++;

            GUI.texttoclientlog();

        } else {

            log("Handshake failed");

        }

    }

}

public static ServerSocket getSs() {
    return ss;
}

public static void setSs(ServerSocket ss) {
    Server.ss = ss;
}

public void log(String logtext) {
    System.out.println(logtext);
    GUI.texttolog(logtext);

}

}

康涅狄格州来自哪里?我想应该是connection.onopen==>connection.sendConnection已建立;相反,那也是错的:谢谢。现在可以了。它以字节为单位接收消息。但我不明白解码器的部分。这是如何工作的?您如何运行您的服务器?我刚刚启动它,它从客户端接收字节129 150 188 10 108 10 255 101 2 100 217 105 24 99 211 100 76 111 207 126 13 104 208 99 31 98 217 110以建立连接。但是我不知道如何解码这个消息,我已经用客户端运行方法更新了我的答案。