我正在尝试开发一个将连接到node.js服务器的android应用程序。这是错误消息:
04-28 14:24:52.250: W/System.err(811): io.socket.SocketIOException: Error while handshaking
04-28 14:24:52.250: W/System.err(811): at io.socket.IOConnection.handshake(IOConnection.java:322)
04-28 14:24:52.259: W/System.err(811): at io.socket.IOConnection.access$600(IOConnection.java:39)
04-28 14:24:52.259: W/System.err(811): at io.socket.IOConnection$ConnectThread.run(IOConnection.java:199)
04-28 14:24:52.259: W/System.err(811): Caused by: java.lang.ArrayIndexOutOfBoundsException
04-28 14:24:52.306: W/System.err(811): at io.socket.IOConnection.handshake(IOConnection.java:318)
04-28 14:24:52.306: W/System.err(811): ... 2 more
服务器:
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(8881, '192.168.1.107');
console.log('Server running at http://192.168.1.107:8881/');
客户端:
public class RestClientActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
SocketIO socket = new SocketIO("http://192.168.1.107:8881/");
socket.connect(new IOCallback() {
@Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
try {
System.out.println("Server said:" + json.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onMessage(String data, IOAcknowledge ack) {
System.out.println("Server said: " + data);
}
@Override
public void onError(SocketIOException socketIOException) {
System.out.println("an Error occured");
socketIOException.printStackTrace();
}
@Override
public void onDisconnect() {
System.out.println("Connection terminated.");
}
@Override
public void onConnect() {
System.out.println("Connection established");
}
@Override
public void on(String event, IOAcknowledge ack, Object... args) {
System.out
.println("Server triggered event '" + event + "'");
}
});
// This line is cached until the connection is establisched.
socket.send("Hello Server!");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
任何想法我做错了什么?如果我在浏览器中输入http://192.168.1.107:8881/
,它会在页面上显示“Hello World”,但我无法使用socket.io-java-client库进行连接。
答案 0 :(得分:2)
首先 IF 您尝试使用socket.io
为您的服务设计休息客户端是不必要的只需坚持使用HTTP服务器就可以了客户端使用HTTPClient ..
假设您使用此android socket.io客户端Java Socket.io client 我也曾与之合作过。
尝试将此作为服务器端套接字io脚本,这是LearnBoost/socket.io
的基本示例var server = require('http').Server();
var io = require('socket.io')(server);
io.on('connection', function(socket){
socket.on('message', function(data){
console.log("Received message : "+data);
socket.emit("message","echoing back : "+data);
});
socket.on('disconnect', function(){
// client disconnected
});
});
server.listen(8881,"192.168.1.107");