【发布时间】:2017-03-09 16:58:10
【问题描述】:
我正在使用 nodejs 服务器、html 和 android 客户端实现套接字消息传递应用程序。所以,我已经实现了以下方式,
第 1 步:使用以下代码创建服务器,该代码运行良好。
const express = require('express');
const app = express();
const server = app.listen(3000,console.log("Socket.io Hello Wolrd server started!"));
const io = require('socket.io')(server);
io.on('connection', (socket) => {
//console.log("Client connected!");
socket.on('chat_sample_test', (msg) => {
console.log(msg.id);
console.log(msg.message);
socket.emit(msg.id, msg.message);
})
});
第 2 步:我已经使用以下代码创建了 HTML 客户端应用程序,它已与服务器连接并且运行良好。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var socket = io("http://192.168.1.138:3000");
socket.on("computer", function(msg) {
document.getElementById('server').innerHTML = msg;
});
$(document).ready(function(){
$("#btnSend").click(function(){
sendMsg();
});
$('#inptBox1').keypress(function (e) {
if (e.which == 13) {
sendMsg();
return false; //<---- Add this line
}
});
});
function sendMsg(){
var message=$("#inptBox1").val();
var messageObj={};
messageObj.id="mobile";
messageObj.message=message;
socket.emit('chat_sample_test', messageObj);
}
</script>
<p id="server" ></p>
<p id="client"></p>
<input type="text" id="inptBox1" placeholder="Enter msg">
<button id="btnSend">Send</button>
</body>
</html>
第 3 步:我已经使用以下代码实现了 Android 客户端,并且它与服务器的连接也可以正常工作。
自定义应用程序类:
public class ChatApplication extends Application {
private Socket mSocket;
{
try {
IO.Options opts = new IO.Options();
opts.forceNew = true;
opts.reconnection = false;
mSocket = IO.socket("http://192.168.1.138:3000");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
public Socket getSocket() {
return mSocket;
}
}
MainActivity 类:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import io.socket.client.Ack;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
EditText messageBox;
Button sendButton;
ListView chatroom;
ChatAdapter chatAdapter;
List<ChatModel> listItems = new ArrayList<>();
private Socket mSocket;
boolean isConnected;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ChatApplication app = (ChatApplication) getApplication();
mSocket = app.getSocket();
mSocket.on(Socket.EVENT_CONNECT, onConnect);
mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.on("mobile",onMessageReceive);
mSocket.connect();
init();
}
void init() {
chatroom = (ListView) findViewById(R.id.chatroom);
sendButton = (Button) findViewById(R.id.sendButton);
messageBox = (EditText) findViewById(R.id.messageBox);
sendButton.setOnClickListener(this);
}
private Emitter.Listener onConnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (!isConnected) {
Toast.makeText(getApplicationContext(),
"Connected", Toast.LENGTH_LONG).show();
isConnected = true;
}
}
});
}
};
private Emitter.Listener onDisconnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
isConnected = false;
Toast.makeText(getApplicationContext(),
"Disconnected", Toast.LENGTH_LONG).show();
}
});
}
};
private Emitter.Listener onConnectError = new Emitter.Listener() {
@Override
public void call(Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Connection Error", Toast.LENGTH_LONG).show();
mSocket.connect();
}
});
}
};
Emitter.Listener onMessageReceive = new Emitter.Listener() {
@Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (args.length > 0) {
JSONObject data = (JSONObject) args[0];
String username="";
String message="";
try {
username = data.getString("username");
message = data.getString("message");
Log.e("RECEIVE",username.concat(" "+message));
setAdapter(username, message);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
}
};
void setAdapter(String name, String message) {
ChatModel chatModel = new ChatModel();
chatModel.setUserName(name);
chatModel.setMessage(message);
listItems.add(chatModel);
if (chatAdapter == null) {
chatAdapter = new ChatAdapter(this, listItems);
chatroom.setAdapter(chatAdapter);
} else {
chatAdapter.notifyDataSetChanged();
}
chatroom.setSelection(chatAdapter.getCount() - 1);
}
private void attemptSend() {
String message = messageBox.getText().toString().trim();
if (TextUtils.isEmpty(message)) {
return;
}
messageBox.setText("");
try {
JSONObject obj = new JSONObject();
obj.put("username", "Hassan");
obj.put("message", message);
obj.put("id", "computer");
mSocket.emit("chat_sample_test", obj, new Ack() {
@Override
public void call(Object... args) {
Toast.makeText(MainActivity.this,"Message received by device",Toast.LENGTH_SHORT).show();
}
});
setAdapter("me", message);
Log.e("SEND",message);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sendButton:
attemptSend();
break;
}
}
@Override
public void onDestroy() {
super.onDestroy();
mSocket.disconnect();
mSocket.off(Socket.EVENT_CONNECT, onConnect);
mSocket.off(Socket.EVENT_DISCONNECT, onDisconnect);
mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.off("mobile", onMessageReceive);
}
}
我的逻辑是,从 html 应用程序,我会将消息发送到移动设备,反之亦然。首先,我已连接到 chat_sample_test 房间。当我尝试使用 html 应用程序发送消息时,服务器会根据我在 nodejs 服务器中添加的控制台打印消息。但手机没有收到消息。移动端出现同样的情况,没有发现错误。
注意:
当我尝试将消息发送到手机时,我已将 id 添加为mobile(手机需要接收消息),而在手机中我已将 id 添加为computer(计算机需要接收消息)
我们将不胜感激。
【问题讨论】:
-
, from the html application, i will send the message to mobile。由于手机是客户端,因此无法将 html javascript 发送到手机。就像 javascript 一样。所以两者都只能向服务器发送数据。 -
感谢您的回复。看,这里,所有的消息都只通过服务器发送。服务器将消息发送到移动设备,反之亦然。
-
然后调整您的帖子,因为它现在令人困惑。写一个清晰的故事。