|
请问socket聊天室,如果我要做一个有N个房间 ,每个房间上限为10人的聊天室怎么做?并发量要高。这个每次客户接进一个房间时候,我需要根据房间号为他安排指定房间号的房间,请问怎么做? |
|
|
楼主去网上下载一个socket聊天室的demo,自己在demo基础上再改改。
|
|
|
找不到啊。没有符合的。没有带房间的 |
|
|
采用NIO来实现,以下是NIO简单示例;你可以通过windows的telnet localhost 8080连接测试.
package com.issrv.nioexample;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class NIOExample {
public static void main(String[] args) throws IOException {
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
ssc.socket().bind(new InetSocketAddress(8080));
Selector s = Selector.open();
ssc.register(s , SelectionKey.OP_ACCEPT).attach(new Acceptable());
//
while(true){
int keyCount = s.select();
if(keyCount > 0){
Iterator<SelectionKey> keys = s.selectedKeys().iterator();
SelectionKey key = keys.next();
keys.remove();
if(!key.isValid()){
continue;
}
if(key.isAcceptable()){
System.out.println("isAcceptable:"+key.attachment());
ServerSocketChannel sschannel = (ServerSocketChannel)key.channel();
SocketChannel schannel = sschannel.accept();
schannel.configureBlocking(false);
schannel.register(s, SelectionKey.OP_WRITE).attach(new Writable());
}
if(key.isReadable()){
SocketChannel schannel = (SocketChannel)key.channel();
System.out.println("isReadable:"+key.attachment());
ByteBuffer bytes = ByteBuffer.allocate(4096);
int c = schannel.read(bytes);
//
if(c == -1){
System.out.println("Disconnection!");
key.channel().close();
}else{
System.out.println(new String(bytes.array(),"UTF-8"));
}
}
if(key.isValid() && key.isWritable()){
System.out.println("isWritable:"+key.attachment());
SocketChannel schannel = (SocketChannel)key.channel();
String text = "Welcome to NIO World!";
ByteBuffer bytes = ByteBuffer.wrap(text.getBytes());
schannel.write(bytes);
schannel.register(s, SelectionKey.OP_READ).attach(new Readable());
}
}
}
}
static class Acceptable{}
static class Readable{}
static class Writable{}
}
|
|
|
每个房间初始化一个端口号,每次连接的时候根据端口号分配
|
|
|
那如何区别多个房间呢? |
|
|
仅仅想做IM的话,下载openfire和spark,采用smack来开发XMPP协议聊天.
|
|
|
有资料吗?我有试过用这个,但是担心不够时间看源码,进行二次开发、真心急求。。openfire结合安卓的游戏房间里面的聊天室 |
|
40分 |
网上Openfire和Spark的资料一大把啊,你可以先拿Spark登陆上去看,或者自己把spark源码下载下来放在eclipse运行调试着看,不难的. |