您的位置:首页 > Web前端 > Node.js

安卓SocketIO+Node.js实现好友与好友间的实时聊天

2016-01-13 19:51 891 查看
1 基础

SocketIo常用API(Node.js端)

1)socket.broadcast.emit('name',json数据);所有接入的人都能收到信息,除了自己

2)socket.emit('name',json数据);一般用于客户端向服务端发送信息

3)socket.join('your room
name');加入一个房间,可以理解为聊天室,好友与好友间就是相当于两个人的聊天室

4)socket.broadcast.to('your
room name').emit('name',json数据);向某个房间发送数据

2
思路


建立连接

1)客户端与服务器建立连接后就用emit发送一个房间号给服务器,房间号一般为自己的ID,要唯一。

2)服务器收到房间号后用join将其加入该房间。

发送消息

1)发送消息的时候将消息和要发送到的房间号用emit提交给服务器

2)服务器收到后用to...emit发送到对应的房间号

接收数据(Node.js端)

socket.on('对应emit中的name', function (data) {
console.log(data.room);//输出信息
socket.join(data.room);//加入房间
});


3 代码

Android

package com.example.socketio;

import io.socket.IOAcknowledge;
import io.socket.IOCallback;
import io.socket.SocketIO;
import io.socket.SocketIOException;

import java.net.MalformedURLException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;

public class MainActivity extends Activity {

private EditText editText;
private EditText editText2;
private ArrayAdapter<String> adapter;
private SocketIO socket;
private Handler handler = new Handler();

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);

adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
ListView listView = (ListView)findViewById(R.id.listView1);
listView.setAdapter(adapter);

editText = (EditText)findViewById(R.id.editText1);//填要发送的消息
editText2 = (EditText)findViewById(R.id.editText2);//进入页面后先用这个editText2发送房间号  然后发送消息的时候再改成要发送的房间号

try {
connect();
} catch(Exception e) {
e.printStackTrace();
}
}

private void connect() throws MalformedURLException{//连接
socket = new SocketIO("http://192.168.1.2:3000");
socket.connect(iocallback);
}

private IOCallback iocallback = new IOCallback() {

@Override
public void onConnect() {
Log.i("IOCallback","onConnect");
}

@Override
public void onDisconnect() {
Log.i("IOCallback","onDisconnect");
}

@Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
Log.i("IOCallback","onMessage: "+json.toString());
}

@Override
public void onMessage(String data, IOAcknowledge ack) {
Log.i("IOCallback","onMessage: "+data);
}

@Override
public void on(String event, IOAcknowledge ack, Object... args) {//接收信息
final JSONObject message = (JSONObject)args[0];

new Thread(new Runnable() {
public void run() {
handler.post(new Runnable() {
public void run() {
try {
if(message.getString("message") != null) {
adapter.insert(message.getString("message"), 0);
}

} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}).start();
}

@Override
public void onError(SocketIOException socketIOException) {
Log.i("IOCallback","onError ");
socketIOException.printStackTrace();
}
};

public void sendEvent(View view){//发送信息
if (editText.getText().toString().length() == 0) {
return;
}

try {
JSONObject json = new JSONObject();
json.put("message", editText.getText().toString());
json.put("from", editText2.getText().toString());
socket.emit("message:send", json);
adapter.insert(editText.getText().toString(), 0);
} catch (JSONException e) {
e.printStackTrace();
}

editText.setText("");
}

public void sendName(View view){//发送房间号
if (editText2.getText().toString().length() == 0) {
return;
}

JSONObject json = new JSONObject();
try {
json.put("room", editText2.getText().toString());
} catch (JSONException e) {
e.printStackTrace();
}
socket.emit("name", json);
}

}


布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/darker_gray"
android:padding="8dp"
android:text="socketIo"
android:textColor="@android:color/white" />

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="10dp" >

<EditText
android:id="@+id/editText1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sendEvent"
android:text="msg" />
</LinearLayout>

<EditText
android:id="@+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="room"
android:onClick="sendName" />

<ListView
android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="301dp" >
</ListView>

</LinearLayout>


添加权限

<uses-permission android:name="android.permission.INTERNET"></uses-permission>


Node.js端 app.js

var http = require("http");

var server = http.createServer().listen(3000, "192.168.1.2");

console.log('Server running at http://192.168.1.2:3000'); 
var io = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {

socket.on('name', function (data) {
console.log(data.room);
socket.join(data.room);
});

socket.on('disconnect', function () {

});

socket.on('message:send', function (data) {

var from = data.from;
console.log(data.message+"  "+from);
socket.broadcast.to(from).emit('message', { 'message':data.message });

});

});


package.json

{
"name":"socketio_example",
"version":"0.0.1",
"private":true,
"dependencies":{
"socket.io":"0.8.7"
}
}


4 运行

1)将package.json与app.js保存在同一目录下,进入目录输入

npm install
下载相应的模块,下载后再输入
node app.js

启动服务器

2)安卓端运行就好 jar包下载地址Socket.jar,安卓的操作顺序在代码中有写
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: