我正在尝试在Android上实现套接字服务器并在Web上实现Socket客户端。我正在关注此Android Socket Server的链接。
以下是代码:
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 6190;
int count = 0;
@Override
public void run() {
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
info.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
String messageFromClient = "";
messageFromClient = dataInputStream.readUTF();
count++;
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n"
+ "Msg from client: " + messageFromClient + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
msg.setText(message);
}
});
String msgReply = "Hello from Android, you are #" + count;
dataOutputStream.writeUTF(msgReply);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
final String errMsg = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
msg.setText(errMsg);
}
});
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
我正在获取设备的本地IP地址(通常为192.168.XX.XX)。 我创建了一个html文件,它使用Web Sockets连接到android Socket服务器。
HTML代码
<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://192.168.1.4:6190");
ws.onopen = function()
{
ws.send("Message to send");
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>
我正在做的事情很少:
我不确定的事情: - HTML代码
我之前没有使用过WebSockets,因此不知道HTML客户端是否存在问题。
如果我在Android设备上关闭服务器,那就是错误
WebSocket connection to 'ws://192.168.1.4:6190/' failed: Connection closed before receiving a handshake response
否则我会在一段时间后收到Timeout错误。