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

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 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(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);
    }

}


布局文件




    

    

        

        

添加权限


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 运行

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

npm install
下载相应的模块,下载后再输入
node app.js
启动服务器

2)安卓端运行就好 jar包下载地址Socket.jar,安卓的操作顺序在代码中有写


你可能感兴趣的:(学习文档,node.js,android,实时聊天,socketIo)