我的目标是在Java Server Socket和浏览器之间建立连接(使用Web套接字)。到目前为止,连接有效,但我的数据流没有。我想从服务器套接字向Web套接字发送一个字符串。
问题是输入和输出流。 Web套接字将“zustimmung”发送到服务器套接字,该套接字在run()
中由in.readLine()
读取。但这不会读取字符串,而是读取“GET / HTTP / 1.1”。
输出也不起作用(我猜它是由于writeUTF())。
所以我的问题:我可以使用哪些数据流在Web套接字和服务器套接字之间传输字符串?
代码服务器:
import java.net.*;
import java.io.*;
public class ServerCommunicator extends Thread{
private final static int PORT = 7777;
private static ServerSocket serverSocket;
private static Server server;
private Socket incoming;
private DataOutputStream out;
private DataInputStream in;
public static void main (String args[])
{
try {
serverSocket = new ServerSocket (PORT);
System.out.println("Waiting for Clients..");
server = new Server();
while (true) {
Socket incoming = serverSocket.accept();
ServerCommunicator communicator = new ServerCommunicator(incoming);
communicator.start();
}
}catch (Exception e) {e.printStackTrace();}
}
public ServerCommunicator (Socket incoming)
{
this.incoming = incoming;
try {
out = new DataOutputStream (incoming.getOutputStream());
in = new DataInputStream (incoming.getInputStream());
} catch (Exception e) {e.printStackTrace();}
}
public void run()
{
try {
String input = in.readLine();
String reply;
reply = server.auszaehlen(input); //returns a String
out.writeUTF(reply);
out.flush();
incoming.close();
} catch (Exception e) {e.printStackTrace();}
}
}
Javascript代码HTML:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function WebSocketTest()
{
if ("WebSocket" in window)
{
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:7777");
ws.onopen = function()
{
// Web Socket is connected, send data using send()
ws.send("zustimmung");
alert("Message is sent...");
};
ws.onmessage = function (evt)
{
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function()
{
// websocket is closed.
alert("Connection is closed...");
};
}
else
{
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id="sse">
<a href="javascript:WebSocketTest()">Run WebSocket</a>
</div>
</body>
</html>
答案 0 :(得分:0)
使用Web套接字连接时,它会发送HTTP请求,这不仅仅是套接字连接。 HTTP请求打开套接字,发送一些元信息,然后发送数据。
您在服务器上阅读的内容是该元信息的第一行。对服务器的典型HTTP请求应该是多行,并且应该如下所示:
GET / HTTP/1.1
Host: example.com
Accept: *
zustimmung
您可能需要读取多个标题行,然后是空行,然后是数据。您的服务器只读一行。您将需要一个循环来读取多行,查找空行,然后读取您的数据。
Wikipedia has good examples请求和响应应该是什么样子。以下是他们的示例回复:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat