我正在尝试一些多人游戏的想法,我正在尝试创建一个Java应用程序来提供基于Web浏览器的多人游戏。
我的开发环境是主机上的Eclipse,以及笔记本电脑上的记事本+谷歌浏览器。
我在客户端使用javascript创建websocket,并在服务器端使用java.net.Socket。
我已经设法在两端确认连接,但似乎无法在客户端关闭连接的情况下发送或接收它们之间的任何数据(甚至没有错误;只是看起来吓坏了某事并调用套接字。关)。
有没有人有任何想法?
这是一些代码:
客户:
<script type="text/javascript">
var socket;
function init() {
socket = new WebSocket("ws://192.168.0.3:10000");
socket.onopen = function() { alert('OPEN: ' + socket.readyState); }
socket.onmessage = function (msg) { alert('DATA: ' + msg.data); }
socket.onerror = function (msg) { alert('DATA: ' + msg.data); }
socket.onclose = function () { alert('CLOSED: ' + socket.readyState); }
}
function onClick() {
socket.send("YAY!");
}
</script>
服务器:
public static void main(String args[])
{
System.out.printLn("Websocket server test");
ServerSocket connectSocket = null;
try
{
Socket clientSocket;
connectSocket = new ServerSocket(10000);
System.out.printLn("Waiting for connection...");
clientSocket = connectSocket.accept();
System.out.printLn("Got one!");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
for(int i=0;i<100;i++) //Shit but easy
{
String data = in.readLine();
System.out.printLn("Got data: " + data);
out.printLn("YAY!");
}
}
catch (IOException e)
{
System.out.printLn("You fail: " + e.getMessage());
}
System.out.printLn("Finished!");
}