我想在android应用程序上创建一个聊天模块。用户和管理员之间的简单聊天,以进行通信。服务器与节点js一起使用。并在客户端使用java-WebSocket-client。
首先,我在节点js上创建Web套接字服务器。
const Messages = require('./models/index').Messages;
const WebSocketServer = require("ws").Server;
module.exports = (server) => {
const wss = new WebSocketServer({server: server});
wss.on("connection", function (ws) {
console.info("websocket connection open");
ws.on("join", function (userId) {
console.log(userId +" : has joined the chat " );
Messages.findAll({
attributes: ['message', 'roomId', 'senderId','createdAt'],
where: { roomId: userId },
order: [ ['createdAt', 'ASC'] ]
}).then(message => {
ws.send('get_last_messages', message);
});
});
ws.on('message', (data) => {
console.log("websocket received a message");
console.log(data);
ws.on("close", function () {
console.log("websocket connection close");
});
});
console.log("websocket server created");
Android chatActivity(实现“ org.java-websocket:Java-WebSocket:1.3.9”):
public class MainActivity extends Activity {
private WebSocketClient mWebSocketClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectWebSocket();
}
private void connectWebSocket() {
URI uri;
try {
uri = new URI("ws://websockethost:8080");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i("Websocket", "Opened");
mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
}
@Override
public void onMessage(String s) {
final String message = s;
runOnUiThread(new Runnable() {
@Override
public void run() {
TextView textView = (TextView)findViewById(R.id.messages);
textView.setText(textView.getText() + "\n" + message);
}
});
}
@Override
public void onClose(int i, String s, boolean b) {
Log.i("Websocket", "Closed " + s);
}
@Override
public void onError(Exception e) {
Log.i("Websocket", "Error " + e.getMessage());
}
};
mWebSocketClient.connect();
}
public void sendMessage(View view) {
EditText editText = (EditText)findViewById(R.id.message);
mWebSocketClient.send(editText.getText().toString());
editText.setText("");
}
但是它不起作用。连接已关闭。
如何正确创建Node.js Websocket服务器和android websocketclient?
答案 0 :(得分:0)
您需要添加Internet权限AndroidManifest.xml
,就像您在MainThread上进行网络通信一样。
https://developer.android.com/training/basics/network-ops/connecting