Javascript客户端无法连接到Java服务器

时间:2016-03-21 06:42:30

标签: javascript java websocket server client

我正在研究一个简单的服务器,只是为了了解它是如何工作的。我有一个java服务器和java客户端工作,但试图让一个javascript客户端连接到同一个java服务器让我发疯!

Java服务器:

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

public class DateServer {

    public static void main(String[] args) throws IOException {
        ServerSocket listener = new ServerSocket(9091);
        System.out.println("Starting");
        try {
            while (true) {
                System.out.println("While");
                Socket socket = listener.accept();
                System.out.println("Accepted");
                BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String msg = input.readLine();
                System.out.println("Message from client: " + msg);
                try {
                    PrintWriter out =
                        new PrintWriter(socket.getOutputStream(), true);

                    System.out.println("Sending message...");
                    out.println("Hi");
                } finally {
                    System.out.println("Closing socket");
                    socket.close();
                }
            }
        }
        finally {
            listener.close();
        }
    }
}

Java客户端:(有效)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JOptionPane;

public class DateClient {

    public static void main(String[] args) throws IOException {
        Socket s = new Socket("localhost", 9091);

        try {
            PrintWriter out =
                new PrintWriter(s.getOutputStream(), true);

            System.out.println("Sending message...");
            out.println("I'm the client");
        } finally {
            //System.out.println("Closing socket");
            //s.close();
        }

        BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String msg = input.readLine();
        System.out.println(msg);
        JOptionPane.showMessageDialog(null, msg);
        s.close();
        System.exit(0);
    }
}

JavaScript客户端:

<!DOCTYPE html>

<html>
<head>
        <title>Echo Test</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width">
    </head>
<body>
<div id="messages"></div>
<script type="text/javascript">

var connection = new WebSocket('ws://localhost:9091/');
var messages = document.getElementById("messages");

// When the connection is open, send some data to the server
connection.onopen = function (e) {
  writeResponse('sent');
  connection.send('Ping');
}

// Log errors
connection.onerror = function (error) {
  writeResponse('Error: ' + error);
}

connection.onclose = function(e){
    writeResponse("Disconnected: " + e.data);
}

// Log messages from the server
connection.onmessage = function (e) {
  writeResponse('Server: ' + e.data);
}

function writeResponse(text){
                messages.innerHTML += "<br/>" + text;
            }

</script>
</body>
</html>

当我使用服务器运行java客户端时:

Starting
While
Accepted
Message from client: I'm the client
Sending message...
Closing socket
While

并从客户端输出:

Sending message...
Hi

这样有效。当我运行javascript客户端时,服务器的输出是:

Starting
While
Accepted
Message from client: GET / HTTP/1.1
Sending message...
Closing socket
While

javascript页面上的输出是:

Error: [object Event]
Disconnected: undefined

另外,firefox控制台说&#34; Firefox无法在ws:// localhost:9091 /&#34;建立与服务器的连接。我错过了什么?谢谢!

1 个答案:

答案 0 :(得分:1)

来自浏览器的webSocket连接不仅仅是普通的TCP连接。它必须支持完整的webSocket协议,否则浏览器将无法连接到它或交换数据。这个完整的webSocket协议包括:

  1. 通过HTTP的初始连接
  2. 升级到webSocket协议
  3. 初始化webSocket连接的安全过程
  4. webSocket数据包格式
  5. 您可以在此处详细了解:getCallingActivity()