引言:
前面专题中介绍了udp、tcp和p2p编程,并且通过一些小的示例来让大家更好的理解它们的工作原理以及怎样.net类库去实现它们的。为了让大家更好的理解我们平常中常见的软件qq的工作原理,所以在本专题中将利用前面专题介绍的知识来实现一个类似qq的聊天程序。
一、即时通信系统
在我们的生活中经常使用即时通信的软件,我们经常接触到的有:qq、阿里旺旺、msn等等。这些都是属于即时通信(instant messenger,im)软件,im是指所有能够即时发送和接收互联网消息的软件。
在前面专题p2p编程中介绍过p2p系统分两种类型——单纯型p2p和混合型p2p(qq就是属于混合型的应用),混合型p2p系统中的服务器(也叫索引服务器)起到协调的作用。在文件共享类应用中,如果采用混合型p2p技术的话,索引服务器就保存着文件信息,这样就可能会造成版权的问题,然而在即时通信类的软件中, 因为客户端传递的都是简单的聊天文本而不是网络媒体资源,这样就不存在版权问题了,在这种情况下,就可以采用混合型p2p技术来实现我们的即时通信软件。前面已经讲了,腾讯的qq就是属于混合型p2p的软件。
因此本专题要实现一个类似qq的聊天程序,其中用到的p2p技术是属于混合型p2p,而不是前一专题中的采用的单纯型p2p技术,同时本程序的实现也会用到tcp、udp编程技术。
二、程序实现的详细设计
本程序采用p2p方式,各个客户端之间直接发消息进行聊天,服务器在其中只是起到协调的作用,下面先理清下程序的流程:
2.1 程序流程设计
当一个新用户通过客户端登陆系统后,从服务器获取当在线的用户信息列表,列表信息包括系统中每个用户的地址,然后用户就可以单独向其他发消息。如果有用户加入或者在线用户退出时,服务器就会及时发消息通知系统中的所有其他客户端,达到它们即时地更新用户信息列表。
根据上面大致的描述,我们可以把系统的流程分为下面几步来更好的理解(大家可以参考qq程序将会更好的理解本程序的流程):
1.用户通过客户端进入系统,向服务器发出消息,请求登陆
2.服务器收到请求后,向客户端返回回应消息,表示同意接受该用户加入,并把自己(指的是服务器)所在监听的端口发送给客户端
3.客户端根据服务器发送过来的端口号和服务器建立连接
4.服务器通过该连接 把在线用户的列表信息发送给新加入的客户端。
5.客户端获得了在线用户列表后就可以自己选择在线用户聊天。(程序中另外设计一个类似qq的聊天窗口来进行聊天)
6.当用户退出系统时也要及时通知服务器,服务器再把这个消息转发给每个在线的用户,使客户端及时更新本地的用户信息列表。
2.2 通信协议设计
所谓协议就是约定,即服务器和客户端之间会话信息的内容格式进行约定,使双方都可以识别,达到更好的通信。
下面就具体介绍下协议的设计:
1. 客户端和服务器之间的对话
(1)登陆过程
① 客户端用匿名udp的方式向服务器发出下面的信息:
login, username, localipendpoint
消息内容包括三个字段,每个字段用 [,]分割,login表示的是请求登陆;username表示用户名;localipendpint表示客户端本地地址。
② 服务器收到后以匿名udp返回下面的回应:
accept, port
其中accept表示服务器接受请求,port表示服务器所在的端口号,服务器监听着这个端口的客户端连接
③ 连接服务器,获取用户列表
客户端从上一步获得了端口号,然后向该端口发起tcp连接,向服务器索取在线用户列表,服务器接受连接后将用户列表传输到客户端。用户列表信息格式如下:
username1,ipendpoint1;username2,ipendpoint2;...;end
username1、username2表示用户名,ipendpoint1,ipendpoint2表示对应的端点,每个用户信息都是由"用户名+端点"组成,用户信息以[;]隔开,整个用户列表以[end]结尾。
(2)注销过程
用户退出时,向服务器发送如下消息:
logout,username,localipendpoint
这条消息看字面意思大家都知道就是告诉服务器 username+localipendpoint这个用户要退出了。
2. 服务器管理用户
(1)新用户加入通知
因为系统中在线的每个用户都有一份当前在线用户表,因此当有新用户登录时,服务器不需要重复地给系统中的每个用户再发送所有用户信息,只需要将新加入用户的信息通知其他用户,其他用户再更新自己的用户列表。
服务器向系统中每个用户广播如下信息:login,username,remoteipendpoint
在这个过程中服务器只是负责将收到的"login"信息转发出去。
(2)用户退出
与新用户加入一样,服务器将用户退出的消息进行广播转发:logout,username,remoteipendpoint
3. 客户端之间聊天
用户进行聊天时,各自的客户端之间是以p2p方式进行工作的,不与服务器有直接联系,这也是p2p技术的特点。
聊天发送的消息格式如下:talk, longtime, selfusername, message
其中,talk表明这是聊天内容的消息;longtime是长时间格式的当前系统时间;selfusername为发送发的用户名;message表示消息的内容。
协议设计介绍完后,下面就进入本程序的具体实现的介绍的。
注:协议是本程序的核心,也是所有软件的核心,每个软件产品的协议都是不一样的,qq有自己的一套协议,msn又有另一套协议,所以使用的qq的用户无法和用msn的朋友进行聊天。
三、程序的实现
服务器端核心代码:
// 启动服务器
// 根据博客中协议的设计部分
// 客户端先向服务器发送登录请求,然后通过服务器返回的端口号
// 再与服务器建立连接
// 所以启动服务按钮事件中有两个套接字:一个是接收客户端信息套接字和
// 监听客户端连接套接字
private void btnstart_click( object sender, eventargs e)
{
// 创建接收套接字
serverip = ipaddress.parse(txbserverip.text);
serveripendpoint = new ipendpoint(serverip, int .parse(txbserverport.text));
receiveudpclient = new udpclient(serveripendpoint);
// 启动接收线程
thread receivethread = new thread(receivemessage);
receivethread.start();
btnstart.enabled = false ;
btnstop.enabled = true ;
// 随机指定监听端口
random random = new random();
tcpport = random.next(port + 1, 65536);
// 创建监听套接字
tcplistener = new tcplistener(serverip, tcpport);
tcplistener.start();
// 启动监听线程
thread listenthread = new thread(listenclientconnect);
listenthread.start();
additemtolistbox( string .format( "服务器线程{0}启动,监听端口{1}" ,serveripendpoint,tcpport));
}
// 接收客户端发来的信息
private void receivemessage()
{
ipendpoint remoteipendpoint = new ipendpoint(ipaddress.any, 0);
while ( true )
{
try
{
// 关闭receiveudpclient时下面一行代码会产生异常
byte [] receivebytes = receiveudpclient.receive( ref remoteipendpoint);
string message = encoding.unicode.getstring(receivebytes, 0, receivebytes.length);
// 显示消息内容
additemtolistbox( string .format( "{0}:{1}" ,remoteipendpoint,message));
// 处理消息数据
// 根据协议的设计部分,从客户端发送来的消息是具有一定格式的
// 服务器接收消息后要对消息做处理
string [] splitstring = message.split( ',' );
// 解析用户端地址
string [] splitsubstring = splitstring[2].split( ':' );
ipendpoint clientipendpoint = new ipendpoint(ipaddress.parse(splitsubstring[0]), int .parse(splitsubstring[1]));
switch (splitstring[0])
{
// 如果是登录信息,向客户端发送应答消息和广播有新用户登录消息
case "login" :
user user = new user(splitstring[1], clientipendpoint);
// 往在线的用户列表添加新成员
userlist.add(user);
additemtolistbox( string .format( "用户{0}({1})加入" , user.getname(), user.getipendpoint()));
string sendstring = "accept," + tcpport.tostring();
// 向客户端发送应答消息
sendtoclient(user, sendstring);
additemtolistbox( string .format( "向{0}({1})发出:[{2}]" , user.getname(), user.getipendpoint(), sendstring));
for ( int i = 0; i < userlist.count; i++)
{
if (userlist[i].getname() != user.getname())
{
// 给在线的其他用户发送广播消息
// 通知有新用户加入
sendtoclient(userlist[i], message);
}
}
additemtolistbox( string .format( "广播:[{0}]" , message));
break ;
case "logout" :
for ( int i = 0; i < userlist.count; i++)
{
if (userlist[i].getname() == splitstring[1])
{
additemtolistbox( string .format( "用户{0}({1})退出" ,userlist[i].getname(),userlist[i].getipendpoint()));
userlist.removeat(i); // 移除用户
}
}
for ( int i = 0; i < userlist.count; i++)
{
// 广播注销消息
sendtoclient(userlist[i], message);
}
additemtolistbox( string .format( "广播:[{0}]" , message));
break ;
}
}
catch
{
// 发送异常退出循环
break ;
}
}
additemtolistbox( string .format( "服务线程{0}终止" , serveripendpoint));
}
// 向客户端发送消息
private void sendtoclient(user user, string message)
{
// 匿名方式发送
sendudpclient = new udpclient(0);
byte [] sendbytes = encoding.unicode.getbytes(message);
ipendpoint remoteipendpoint =user.getipendpoint();
sendudpclient.send(sendbytes,sendbytes.length,remoteipendpoint);
sendudpclient.close();
}
// 接受客户端的连接
private void listenclientconnect()
{
tcpclient newclient = null ;
while ( true )
{
try
{
newclient = tcplistener.accepttcpclient();
additemtolistbox( string .format( "接受客户端{0}的tcp请求" ,newclient.client.remoteendpoint));
}
catch
{
additemtolistbox( string .format( "监听线程({0}:{1})" , serverip, tcpport));
break ;
}
thread sendthread = new thread(senddata);
sendthread.start(newclient);
}
}
// 向客户端发送在线用户列表信息
// 服务器通过tcp连接把在线用户列表信息发送给客户端
private void senddata( object userclient)
{
tcpclient newuserclient = (tcpclient)userclient;
userliststring = null ;
for ( int i = 0; i < userlist.count; i++)
{
userliststring += userlist[i].getname() + ","
+ userlist[i].getipendpoint().tostring() + ";" ;
}
userliststring += "end" ;
networkstream = newuserclient.getstream();
binarywriter = new binarywriter(networkstream);
binarywriter.write(userliststring);
binarywriter.flush();
additemtolistbox( string .format( "向{0}发送[{1}]" , newuserclient.client.remoteendpoint, userliststring));
binarywriter.close();
newuserclient.close();
}
客户端核心代码:
// 登录服务器
private void btnlogin_click( object sender, eventargs e)
{
// 创建接受套接字
ipaddress clientip = ipaddress.parse(txtlocalip.text);
clientipendpoint = new ipendpoint(clientip, int .parse(txtlocalport.text));
receiveudpclient = new udpclient(clientipendpoint);
// 启动接收线程
thread receivethread = new thread(receivemessage);
receivethread.start();
// 匿名发送
sendudpclient = new udpclient(0);
// 启动发送线程
thread sendthread = new thread(sendmessage);
sendthread.start( string .format( "login,{0},{1}" , txtusername.text, clientipendpoint));
btnlogin.enabled = false ;
btnlogout.enabled = true ;
this .text = txtusername.text;
}
// 客户端接受服务器回应消息
private void receivemessage()
{
ipendpoint remoteipendpoint = new ipendpoint(ipaddress.any,0);
while ( true )
{
try
{
// 关闭receiveudpclient时会产生异常
byte [] receivebytes = receiveudpclient.receive( ref remoteipendpoint);
string message = encoding.unicode.getstring(receivebytes,0,receivebytes.length);
// 处理消息
string [] splitstring = message.split( ',' );
switch (splitstring[0])
{
case "accept" :
try
{
tcpclient = new tcpclient();
tcpclient.connect(remoteipendpoint.address, int .parse(splitstring[1]));
if (tcpclient != null )
{
// 表示连接成功
networkstream = tcpclient.getstream();
binaryreader = new binaryreader(networkstream);
}
}
catch
{
messagebox.show( "连接失败" , "异常" );
}
thread getuserlistthread = new thread(getuserlist);
getuserlistthread.start();
break ;
case "login" :
string useritem = splitstring[1] + "," + splitstring[2];
additemtolistview(useritem);
break ;
case "logout" :
removeitemfromlistview(splitstring[1]);
break ;
case "talk" :
for ( int i = 0; i < chatformlist.count; i++)
{
if (chatformlist[i].text == splitstring[2])
{
chatformlist[i].showtalkinfo(splitstring[2], splitstring[1], splitstring[3]);
}
}
break ;
}
}
catch
{
break ;
}
}
}
// 从服务器获取在线用户列表
private void getuserlist()
{
while ( true )
{
userliststring = null ;
try
{
userliststring = binaryreader.readstring();
if (userliststring.endswith( "end" ))
{
string [] splitstring = userliststring.split( ';' );
for ( int i = 0; i < splitstring.length - 1; i++)
{
additemtolistview(splitstring[i]);
}
binaryreader.close();
tcpclient.close();
break ;
}
}
catch
{
break ;
}
}
}
// 发送登录请求
private void sendmessage( object obj)
{
string message = ( string )obj;
byte [] sendbytes = encoding.unicode.getbytes(message);
ipaddress remoteip = ipaddress.parse(txtserverip.text);
ipendpoint remoteipendpoint = new ipendpoint(remoteip, int .parse(txtserverport.text));
sendudpclient.send(sendbytes, sendbytes.length, remoteipendpoint);
sendudpclient.close();
}
程序的运行结果:
首先先运行服务器窗口,在服务器窗口点击[启动]按钮来启动服务器,然后客户端首先指定服务器的端口号,修改用户名(这里也可以不修改,使用默认的也可以),然后点击[登录]按钮来登陆服务器(也就是告诉服务器本地的客户端地址),然后从服务器端获得在线用户列表,界面演示如下:
然后用户可以双击在线用户进行聊天(此程序支持与多人进行聊天),下面是功能的演示图片:
双方进行聊天时,这里没有实现像qq一样,有人发信息来在对应的客户端就有消息提醒的功能的, 所以双方进行聊天的过程中,每个客户端都需要在在线用户列表中点击聊天的对象来激活聊天对话框(意思就是从图片中可以看出[天涯]客户端想和剑痴聊天的话,就在[在线用户]列表双击剑痴来激活聊天窗口,同时[剑痴]客户端也必须双击[天涯]来激活聊天窗口,这样双方就看到对方发来的信息了,(不激活窗口,也是发送了信息,只是没有一个窗口来进行显示)),而且从图片中也可以看出——此程序支持与多人聊天,即天涯同时与[剑痴]和"大地"同时聊天。
本程序的源代码链接: demo
四、总结
本专题介绍了如何去实现一个类似qq的聊天程序,一方面让大家可以巩固前面专题的内容,另一方面让大家更好的理解即时通信软件(腾讯qq)的工作原理和软件协议的设计。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/zhili/archive/2012/09/23/QQ_P2P.html
dy("nrwz");
查看更多关于详解C# 网络编程系列:实现类似QQ的即时通信程序的详细内容...