用Remoting开发的P2P聊天软件,如何解决公网上两个不同局域网之间通信的问题呢?

时间:2021-03-17 20:12:35
知道局域网的IP地址好办,但在公网上呢?局域网里多台机器一个公网IP,怎么实现和外网的点对点聊天呢?

13 个解决方案

#1


需要一台公网服务器

#2


up

#3


网络地址转换,需要合法ip

#4


up

#5


nat(network address translators),网络地址转换:网络地址转换是在ip地址日益缺乏的情况下产生的,它的主要目的就是为了能够地址重用。nat分为两大类,基本的nat和napt(network address/port translator)。
    最开始nat是运行在路由器上的一个功能模块。
    最先提出的是基本的nat,它的产生基于如下事实:一个私有网络(域)中的节点中只有很少的节点需要与外网连接(呵呵,这是在上世纪90年代中期提出的)。那么这个子网中其实只有少数的节点需要全球唯一的ip地址,其他的节点的ip地址应该是可以重用的。
因此,基本的nat实现的功能很简单,在子网内使用一个保留的ip子网段,这些ip对外是不可见的。子网内只有少数一些ip地址可以对应到真正全球唯一的ip地址。如果这些节点需要访问外部网络,那么基本nat就负责将这个节点的子网内ip转化为一个全球唯一的ip然后发送出去。(基本的nat会改变ip包中的原ip地址,但是不会改变ip包中的端口)
    关于基本的nat可以参看rfc 1631
另外一种nat叫做napt,从名称上我们也可以看得出,napt不但会改变经过这个nat设备的ip数据报的ip地址,还会改变ip数据报的tcp/udp端口。基本nat的设备可能我们见的不多(呵呵,我没有见到过),napt才是我们真正讨论的主角。看下图:
有一个私有网络10.*.*.*,client a是其中的一台计算机,这个网络的网关(一个nat设备)的外网ip是155.99.25.11(应该还有一个内网的ip地址,比如10.0.0.10)。如果client a中的某个进程(这个进程创建了一个udp socket,这个socket绑定1234端口)想访问外网主机18.181.0.31的1235端口,那么当数据包通过nat时会发生什么事情呢?
先nat会改变这个数据包的原ip地址,改为155.99.25.11。接着nat会为这个传输创建一个session(session是一个抽象的概念,如果是tcp,也许session是由一个syn包开始,以一个fin包结束。而udp呢,以这个ip的这个端口的第一个udp开始,结束呢,呵呵,也许是几分钟,也许是几小时,这要看具体的实现了)并且给这个session分配一个端口,比如62000,然后改变这个数据包的源端口为62000。所以本来是(10.0.0.1:1234->18.181.0.31:1235)的数据包到了互联网上变为了(155.99.25.11:62000->18.181.0.31:1235)。一旦nat创建了一个session后,nat会记住62000端口对应的是10.0.0.1的1234端口,以后从18.181.0.31发送到62000端口的数据会被nat自动的转发到10.0.0.1上。(注意:这里是说18.181.0.31发送到62000端口的数据会被转发,其他的ip发送到这个端口的数据将被nat抛弃)这样client a就与server s1建立以了一个连接。
呵呵,上面的基础知识可能很多人都知道了,那么下面是关键的部分了。
看看下面的情况:
接上面的例子,如果client a的原来那个socket(绑定了1234端口的那个udp socket)又接着向另外一个server s2发送了一个udp包,那么这个udp包在通过nat时会怎么样呢?
    这时可能会有两种情况发生,一种是nat再次创建一个session,并且再次为这个session分配一个端口号(比如:62001)。另外一种是nat再次创建一个session,但是不会新分配一个端口号,而是用原来分配的端口号62000。前一种nat叫做symmetric nat,后一种叫做cone nat。我们期望我们的nat是第二种,呵呵,如果你的nat刚好是第一种,那么很可能会有很多p2p软件失灵。(可以庆幸的是,现在绝大多数的nat属于后者,即cone nat)
    好了,我们看到,通过nat,子网内的计算机向外连结是很容易的(nat相当于透明的,子网内的和外网的计算机不用知道nat的情况)。
但是如果外部的计算机想访问子网内的计算机就比较困难了(而这正是p2p所需要的)。
那么我们如果想从外部发送一个数据报给内网的计算机有什么办法呢?首先,我们必须在内网的nat上打上一个“洞”(也就是前面我们说的在nat上建立一个session),这个洞不能由外部来打,只能由内网内的主机来打。而且这个洞是有方向的,比如从内部某台主机(比如:192.168.0.10)向外部的某个ip(比如:219.237.60.1)发送一个udp包,那么就在这个内网的nat设备上打了一个方向为219.237.60.1的“洞”,(这就是称为udp hole punching的技术)以后219.237.60.1就可以通过这个洞与内网的192.168.0.10联系了。(但是其他的ip不能利用这个洞)。
呵呵,现在该轮到我们的正题p2p了。有了上面的理论,实现两个内网的主机通讯就差最后一步了:那就是鸡生蛋还是蛋生鸡的问题了,两边都无法主动发出连接请求,谁也不知道谁的公网地址,那我们如何来打这个洞呢?我们需要一个中间人来联系这两个内网主机。
现在我们来看看一个p2p软件的流程,以下图为例:
首先,client a登录服务器,nat a为这次的session分配了一个端口60000,那么server s收到的client a的地址是202.187.45.3:60000,这就是client a的外网地址了。同样,client b登录server s,nat b给此次session分配的端口是40000,那么server s收到的b的地址是187.34.1.56:40000。此时,client a与client b都可以与server s通信了。如果client a此时想直接发送信息给client b,那么他可以从server s那儿获得b的公网地址187.34.1.56:40000,是不是client a向这个地址发送信息client b就能收到了呢?答案是不行,因为如果这样发送信息,nat b会将这个信息丢弃(因为这样的信息是不请自来的,为了安全,大多数nat都会执行丢弃动作)。现在我们需要的是在nat b上打一个方向为202.187.45.3(即client a的外网地址)的洞,那么client a发送到187.34.1.56:40000的信息,client b就能收到了。这个打洞命令由谁来发呢,呵呵,当然是server s。
总结一下这个过程:如果client a想向client b发送信息,那么client a发送命令给server s,请求server s命令client b向client a方向打洞。呵呵,是不是很绕口,不过没关系,想一想就很清楚了,何况还有源代码呢(侯老师说过:在源代码面前没有秘密 8)),然后client a就可以通过client b的外网地址与client b通信了。
    注意:以上过程只适合于cone nat的情况,如果是symmetric nat,那么当client b向client a打洞的端口已经重新分配了,client b将无法知道这个端口(如果symmetric nat的端口是顺序分配的,那么我们或许可以猜测这个端口号,可是由于可能导致失败的因素太多,我们不推荐这种猜测端口的方法)。    
下面是一个模拟p2p聊天的过程的源代码,过程很简单,p2pserver运行在一个拥有公网ip的计算机上,p2pclient运行在两个不同的nat后(注意,如果两个客户端运行在一个nat后,本程序很可能不能运行正常,这取决于你的nat是否支持loopback translation,详见http://midcom-p2p.sourceforge.net/draft-ford-midcom-p2p-01.txt,当然,此问题可以通过双方先尝试连接对方的内网ip来解决,但是这个代码只是为了验证原理,并没有处理这些问题),后登录的计算机可以获得先登录计算机的用户名,后登录的计算机通过send username message的格式来发送消息。如果发送成功,说明你已取得了直接与对方连接的成功。

#6


源代码
1.  wellknown公用库
namespace p2p.wellknown
{
using system;
using system.io;
using system.runtime.serialization.formatters.binary;
/// <summary>
/// p2pconsts 的摘要说明。
/// </summary>
public class p2pconsts
{
/// <summary>
/// 服务器侦听端口号
/// </summary>
public const int srv_port  = 2280;
}
/// <summary>
/// user 的摘要说明。
/// </summary>
[serializable]
public class user
{
protected string username;
protected ipendpoint netpoint;
 
public user(string username, ipendpoint netpoint)
{
this.username = username;
this.netpoint = netpoint;
}
public string username
{
get { return username; }
}
 
public ipendpoint netpoint
{
get { return netpoint; }
set { netpoint = value;}
}
}
/// <summary>
/// usercollection 的摘要说明。
/// </summary>
[serializable]
public class usercollection : collectionbase
{
public void add(user user)
{
innerlist.add(user);
}
 
public void remove(user user)
{
innerlist.remove(user);
}
 
public user this[int index]
{
get { return (user)innerlist[index]; }
}
 
public user find(string username)
{
foreach(user user in this)
{
if (string.compare(username, user.username, true) == 0)
{
return user;
}
}
return null;
}
}
/// <summary>
/// formatterhelper 序列化,反序列化消息的帮助类
/// </summary>
public class formatterhelper
{
public static byte[] serialize(object obj)
{
binaryformatter binaryf = new binaryformatter();
memorystream ms = new memorystream(1024*10);
binaryf.serialize(ms, obj);
ms.seek(0, seekorigin.begin);
byte[] buffer = new byte[(int)ms.length];
ms.read(buffer, 0, buffer.length);
ms.close();
return buffer;
}
 
public static object deserialize(byte[] buffer)
{
binaryformatter binaryf = new binaryformatter();
memorystream ms = new memorystream(buffer, 0, buffer.length, false);
object obj = binaryf.deserialize(ms);
ms.close();
return obj;
}
}
/// <summary>
/// message base class
/// </summary>
[system.serializable]
public abstract class messagebase
{
}
 
// message from client to server
namespace c2s
{
/// <summary>
/// 客户端发送到服务器的消息基类
/// </summary>
public abstract class csmessage : messagebase
{
private string username;
protected csmessage(string anusername)
{
username = anusername;
}
public string username
{
get { return username; }
}
}
/// <summary>
/// 用户登录消息
/// </summary>
public class loginmessage : csmessage
{
private string password;
public loginmessage(string username, string password) : base(username)
{
this.password = password;
}
public string password
{
get { return password; }
}
}
/// <summary>
/// 用户登出消息
/// </summary>
public class logoutmessage : csmessage
{
public logoutmessage(string username) : base(username)
{}
}
/// <summary>
/// 请求用户列表消息
/// </summary>
public class getusersmessage : csmessage
{
public getusersmessage(string username) : base(username)
{}
}
/// <summary>
/// 请求purch hole消息
/// </summary>
public class translatemessage : csmessage
{
protected string tousername;
public translatemessage(string username, string touser name) : base(username)
{
this.tousername = tousername;
}
public string tousername
{
get { return this.tousername; }
}
}
}
 
// message from server to the client
namespace s2c
{
/// <summary>
/// 服务器发送到客户端消息基类
/// </summary>
public abstract class scmessage : messagebase
{}
/// <summary>
/// 请求用户列表应答消息
/// </summary>
public class getusersresponsemessage : scmessage
{
private usercollection userlist;
public getusersresponsemessage(usercollection users)
{
this.userlist = users;
}
public usercollection userlist
{
get { return userlist; }
}
}
/// <summary>
/// 转发请求purch hole消息
/// </summary>
public class someonecallyoumessage : scmessage
{
protected system.net.ipendpoint remotepoint;
public someonecallyoumessage(system.net.ipendpoint point)
{
this.remotepoint = point;
}
public system.net.ipendpoint remotepoint
{
get { return remotepoint; }
}
}
}
 
// message from peer to the peer

#7


namespace p2p
{
/// <summary>
/// 点对点消息基类
/// </summary>
public abstract class ppmessage : messagebase
{}
/// <summary>
/// 测试消息
/// </summary>
public class workmessage : ppmessage
{
private string message;
public workmessage(string msg)
{
message = msg;
}
public string message
{
get { return message; }
}
}
/// <summary>
/// 测试应答消息
/// </summary>
public class ackmessage : ppmessage
{
}
/// <summary>
/// p2p purch hole message
/// </summary>
public class trashmessage : ppmessage
{}
}
}
 
 
2.  p2pserver
namespace p2p.p2pserver
{
using system;
using system.net;
using system.net.sockets;
using system.threading;
using p2p.wellknown;
/// <summary>
/// appclass 的摘要说明。
/// </summary>
public class appclass
{
public static void main()
{
server server = new server();
try
{
server.start();
console.readline();
server.stop();
}
catch
{
}
}
}
/// <summary>
/// server 的摘要说明。
/// </summary>
public class server
{
private udpclient server;
private usercollection userlist;
private thread serverthread;
private ipendpoint remotepoint;
 
public server()
{
userlist = new usercollection();
remotepoint = new ipendpoint(ipaddress.any, 0);
serverthread = new thread(new threadstart(run));
}
 
public void start()
{
try
{
server = new udpclient(p2pconsts.srv_port);
serverthread.start();
console.writeline("p2p server started, waiting client connect...");
}
catch(exception exp)
{
console.writeline("start p2p server error: " + exp.message);
throw exp;
}
}
 
public void stop()
{
console.writeline("p2p server stopping...");
try
{
serverthread.abort();
server.close();
console.writeline("stop ok.");
}
catch(exception exp)
{
console.writeline("stop error: " + exp.message);
throw exp;
}
 
}
 
private void run()
{
byte[] buffer = null;
while (true)
{
byte[] msgbuffer = server.receive(ref remotepoint);
try
{
object msgobj = formatterhelper.deserialize(msgbuffer);
type msgtype = msgobj.gettype();
if (msgtype == typeof(p2p.wellknown.c2s.loginmessage))
{
// 转换接受的消息
p2p.wellknown.c2s.loginmessage lginmsg = (p2p.wellknown.c2s.loginmessage)msgobj;
console.writeline("has an user login: {0}", lginmsg.username);
// 添加用户到列表
ipendpoint userendpoint = new ipendpoint(remotepoint.address, remotepoint.port);
user user = new user(lginmsg.username, userendpoint);
userlist.add(user);
// 发送应答消息
p2p.wellknown.s2c.getusersresponsemessage usersmsg = new p2p.wellknown.s2c.getusersresponsemessage(userlist);
buffer = formatterhelper.serialize(usersmsg);
server.send(buffer, buffer.length, remotepoint);
}
else if (msgtype == typeof(p2p.wellknown.c2s.logoutmessage))
{
// 转换接受的消息
p2p.wellknown.c2s.logoutmessage lgoutmsg = (p2p.wellknown.c2s.logoutmessage)msgobj;
console.writeline("has an user logout: {0}", lgoutmsg.username);
// 从列表中删除用户
user lgoutuser = userlist.find(lgoutmsg.username);
if (lgoutuser != null)
{
userlist.remove(lgoutuser);
}
}
else if (msgtype == typeof(p2p.wellknown.c2s.translatemessage))
{
// 转换接受的消息
p2p.wellknown.c2s.translatemessage transmsg = (p2p.wellknown.c2s.translatemessage)msgobj;
console.writeline("{0}(1) wants to p2p {2}", remotepoint.address.tostring(), transmsg.username, transmsg.tousername);
// 获取目标用户
user touser = userlist.find(transmsg.tousername);
// 转发purch hole请求消息
if (touser == null)
{
console.writeline("remote host {0} cannot be found at index server", transmsg.tousername);
}
else
{
p2p.wellknown.s2c.someonecallyoumessage transmsg = new p2p.wellknown.s2c.someonecallyoumessage(remotepoint);
buffer = formatterhelper.serialize(transmsg);
server.send(buffer, buffer.length, touser.netpoint);
}
}
else if (msgtype == typeof(p2p.wellknown.c2s.getusersmessage))
{
// 发送当前用户信息到所有登录客户
p2p.wellknown.s2c.getusersresponsemessage srvresmsg = new p2p.wellknown.s2c.getusersresponsemessage(userlist);
buffer = formatterhelper.serialize(srvresmsg);
foreach(user user in userlist)
{
server.send(buffer, buffer.length, user.netpoint);
}
}
thread.sleep(500);
}
catch{}
}
}
}
}
 
 

#8


学习

#9


mark

#10


公司上班不能用QQ和MSN,实在是无聊,就自己做了一个局域网的聊天工具。
有兴趣的朋友可以试试看。

不需要建立服务器!!!

名称:EasyMessenger
版本:2006 第2版

主要功能介绍:
 点对点私聊
 多人群聊
 自定义表情
 发送网络图片
 即时传送文件
 历史记录保存

有需要的朋友可以来信,可以自己定义需要的群组。

下载页面:
http://www.easymessenger.cn

#11


up

#12


up

#1


需要一台公网服务器

#2


up

#3


网络地址转换,需要合法ip

#4


up

#5


nat(network address translators),网络地址转换:网络地址转换是在ip地址日益缺乏的情况下产生的,它的主要目的就是为了能够地址重用。nat分为两大类,基本的nat和napt(network address/port translator)。
    最开始nat是运行在路由器上的一个功能模块。
    最先提出的是基本的nat,它的产生基于如下事实:一个私有网络(域)中的节点中只有很少的节点需要与外网连接(呵呵,这是在上世纪90年代中期提出的)。那么这个子网中其实只有少数的节点需要全球唯一的ip地址,其他的节点的ip地址应该是可以重用的。
因此,基本的nat实现的功能很简单,在子网内使用一个保留的ip子网段,这些ip对外是不可见的。子网内只有少数一些ip地址可以对应到真正全球唯一的ip地址。如果这些节点需要访问外部网络,那么基本nat就负责将这个节点的子网内ip转化为一个全球唯一的ip然后发送出去。(基本的nat会改变ip包中的原ip地址,但是不会改变ip包中的端口)
    关于基本的nat可以参看rfc 1631
另外一种nat叫做napt,从名称上我们也可以看得出,napt不但会改变经过这个nat设备的ip数据报的ip地址,还会改变ip数据报的tcp/udp端口。基本nat的设备可能我们见的不多(呵呵,我没有见到过),napt才是我们真正讨论的主角。看下图:
有一个私有网络10.*.*.*,client a是其中的一台计算机,这个网络的网关(一个nat设备)的外网ip是155.99.25.11(应该还有一个内网的ip地址,比如10.0.0.10)。如果client a中的某个进程(这个进程创建了一个udp socket,这个socket绑定1234端口)想访问外网主机18.181.0.31的1235端口,那么当数据包通过nat时会发生什么事情呢?
先nat会改变这个数据包的原ip地址,改为155.99.25.11。接着nat会为这个传输创建一个session(session是一个抽象的概念,如果是tcp,也许session是由一个syn包开始,以一个fin包结束。而udp呢,以这个ip的这个端口的第一个udp开始,结束呢,呵呵,也许是几分钟,也许是几小时,这要看具体的实现了)并且给这个session分配一个端口,比如62000,然后改变这个数据包的源端口为62000。所以本来是(10.0.0.1:1234->18.181.0.31:1235)的数据包到了互联网上变为了(155.99.25.11:62000->18.181.0.31:1235)。一旦nat创建了一个session后,nat会记住62000端口对应的是10.0.0.1的1234端口,以后从18.181.0.31发送到62000端口的数据会被nat自动的转发到10.0.0.1上。(注意:这里是说18.181.0.31发送到62000端口的数据会被转发,其他的ip发送到这个端口的数据将被nat抛弃)这样client a就与server s1建立以了一个连接。
呵呵,上面的基础知识可能很多人都知道了,那么下面是关键的部分了。
看看下面的情况:
接上面的例子,如果client a的原来那个socket(绑定了1234端口的那个udp socket)又接着向另外一个server s2发送了一个udp包,那么这个udp包在通过nat时会怎么样呢?
    这时可能会有两种情况发生,一种是nat再次创建一个session,并且再次为这个session分配一个端口号(比如:62001)。另外一种是nat再次创建一个session,但是不会新分配一个端口号,而是用原来分配的端口号62000。前一种nat叫做symmetric nat,后一种叫做cone nat。我们期望我们的nat是第二种,呵呵,如果你的nat刚好是第一种,那么很可能会有很多p2p软件失灵。(可以庆幸的是,现在绝大多数的nat属于后者,即cone nat)
    好了,我们看到,通过nat,子网内的计算机向外连结是很容易的(nat相当于透明的,子网内的和外网的计算机不用知道nat的情况)。
但是如果外部的计算机想访问子网内的计算机就比较困难了(而这正是p2p所需要的)。
那么我们如果想从外部发送一个数据报给内网的计算机有什么办法呢?首先,我们必须在内网的nat上打上一个“洞”(也就是前面我们说的在nat上建立一个session),这个洞不能由外部来打,只能由内网内的主机来打。而且这个洞是有方向的,比如从内部某台主机(比如:192.168.0.10)向外部的某个ip(比如:219.237.60.1)发送一个udp包,那么就在这个内网的nat设备上打了一个方向为219.237.60.1的“洞”,(这就是称为udp hole punching的技术)以后219.237.60.1就可以通过这个洞与内网的192.168.0.10联系了。(但是其他的ip不能利用这个洞)。
呵呵,现在该轮到我们的正题p2p了。有了上面的理论,实现两个内网的主机通讯就差最后一步了:那就是鸡生蛋还是蛋生鸡的问题了,两边都无法主动发出连接请求,谁也不知道谁的公网地址,那我们如何来打这个洞呢?我们需要一个中间人来联系这两个内网主机。
现在我们来看看一个p2p软件的流程,以下图为例:
首先,client a登录服务器,nat a为这次的session分配了一个端口60000,那么server s收到的client a的地址是202.187.45.3:60000,这就是client a的外网地址了。同样,client b登录server s,nat b给此次session分配的端口是40000,那么server s收到的b的地址是187.34.1.56:40000。此时,client a与client b都可以与server s通信了。如果client a此时想直接发送信息给client b,那么他可以从server s那儿获得b的公网地址187.34.1.56:40000,是不是client a向这个地址发送信息client b就能收到了呢?答案是不行,因为如果这样发送信息,nat b会将这个信息丢弃(因为这样的信息是不请自来的,为了安全,大多数nat都会执行丢弃动作)。现在我们需要的是在nat b上打一个方向为202.187.45.3(即client a的外网地址)的洞,那么client a发送到187.34.1.56:40000的信息,client b就能收到了。这个打洞命令由谁来发呢,呵呵,当然是server s。
总结一下这个过程:如果client a想向client b发送信息,那么client a发送命令给server s,请求server s命令client b向client a方向打洞。呵呵,是不是很绕口,不过没关系,想一想就很清楚了,何况还有源代码呢(侯老师说过:在源代码面前没有秘密 8)),然后client a就可以通过client b的外网地址与client b通信了。
    注意:以上过程只适合于cone nat的情况,如果是symmetric nat,那么当client b向client a打洞的端口已经重新分配了,client b将无法知道这个端口(如果symmetric nat的端口是顺序分配的,那么我们或许可以猜测这个端口号,可是由于可能导致失败的因素太多,我们不推荐这种猜测端口的方法)。    
下面是一个模拟p2p聊天的过程的源代码,过程很简单,p2pserver运行在一个拥有公网ip的计算机上,p2pclient运行在两个不同的nat后(注意,如果两个客户端运行在一个nat后,本程序很可能不能运行正常,这取决于你的nat是否支持loopback translation,详见http://midcom-p2p.sourceforge.net/draft-ford-midcom-p2p-01.txt,当然,此问题可以通过双方先尝试连接对方的内网ip来解决,但是这个代码只是为了验证原理,并没有处理这些问题),后登录的计算机可以获得先登录计算机的用户名,后登录的计算机通过send username message的格式来发送消息。如果发送成功,说明你已取得了直接与对方连接的成功。

#6


源代码
1.  wellknown公用库
namespace p2p.wellknown
{
using system;
using system.io;
using system.runtime.serialization.formatters.binary;
/// <summary>
/// p2pconsts 的摘要说明。
/// </summary>
public class p2pconsts
{
/// <summary>
/// 服务器侦听端口号
/// </summary>
public const int srv_port  = 2280;
}
/// <summary>
/// user 的摘要说明。
/// </summary>
[serializable]
public class user
{
protected string username;
protected ipendpoint netpoint;
 
public user(string username, ipendpoint netpoint)
{
this.username = username;
this.netpoint = netpoint;
}
public string username
{
get { return username; }
}
 
public ipendpoint netpoint
{
get { return netpoint; }
set { netpoint = value;}
}
}
/// <summary>
/// usercollection 的摘要说明。
/// </summary>
[serializable]
public class usercollection : collectionbase
{
public void add(user user)
{
innerlist.add(user);
}
 
public void remove(user user)
{
innerlist.remove(user);
}
 
public user this[int index]
{
get { return (user)innerlist[index]; }
}
 
public user find(string username)
{
foreach(user user in this)
{
if (string.compare(username, user.username, true) == 0)
{
return user;
}
}
return null;
}
}
/// <summary>
/// formatterhelper 序列化,反序列化消息的帮助类
/// </summary>
public class formatterhelper
{
public static byte[] serialize(object obj)
{
binaryformatter binaryf = new binaryformatter();
memorystream ms = new memorystream(1024*10);
binaryf.serialize(ms, obj);
ms.seek(0, seekorigin.begin);
byte[] buffer = new byte[(int)ms.length];
ms.read(buffer, 0, buffer.length);
ms.close();
return buffer;
}
 
public static object deserialize(byte[] buffer)
{
binaryformatter binaryf = new binaryformatter();
memorystream ms = new memorystream(buffer, 0, buffer.length, false);
object obj = binaryf.deserialize(ms);
ms.close();
return obj;
}
}
/// <summary>
/// message base class
/// </summary>
[system.serializable]
public abstract class messagebase
{
}
 
// message from client to server
namespace c2s
{
/// <summary>
/// 客户端发送到服务器的消息基类
/// </summary>
public abstract class csmessage : messagebase
{
private string username;
protected csmessage(string anusername)
{
username = anusername;
}
public string username
{
get { return username; }
}
}
/// <summary>
/// 用户登录消息
/// </summary>
public class loginmessage : csmessage
{
private string password;
public loginmessage(string username, string password) : base(username)
{
this.password = password;
}
public string password
{
get { return password; }
}
}
/// <summary>
/// 用户登出消息
/// </summary>
public class logoutmessage : csmessage
{
public logoutmessage(string username) : base(username)
{}
}
/// <summary>
/// 请求用户列表消息
/// </summary>
public class getusersmessage : csmessage
{
public getusersmessage(string username) : base(username)
{}
}
/// <summary>
/// 请求purch hole消息
/// </summary>
public class translatemessage : csmessage
{
protected string tousername;
public translatemessage(string username, string touser name) : base(username)
{
this.tousername = tousername;
}
public string tousername
{
get { return this.tousername; }
}
}
}
 
// message from server to the client
namespace s2c
{
/// <summary>
/// 服务器发送到客户端消息基类
/// </summary>
public abstract class scmessage : messagebase
{}
/// <summary>
/// 请求用户列表应答消息
/// </summary>
public class getusersresponsemessage : scmessage
{
private usercollection userlist;
public getusersresponsemessage(usercollection users)
{
this.userlist = users;
}
public usercollection userlist
{
get { return userlist; }
}
}
/// <summary>
/// 转发请求purch hole消息
/// </summary>
public class someonecallyoumessage : scmessage
{
protected system.net.ipendpoint remotepoint;
public someonecallyoumessage(system.net.ipendpoint point)
{
this.remotepoint = point;
}
public system.net.ipendpoint remotepoint
{
get { return remotepoint; }
}
}
}
 
// message from peer to the peer

#7


namespace p2p
{
/// <summary>
/// 点对点消息基类
/// </summary>
public abstract class ppmessage : messagebase
{}
/// <summary>
/// 测试消息
/// </summary>
public class workmessage : ppmessage
{
private string message;
public workmessage(string msg)
{
message = msg;
}
public string message
{
get { return message; }
}
}
/// <summary>
/// 测试应答消息
/// </summary>
public class ackmessage : ppmessage
{
}
/// <summary>
/// p2p purch hole message
/// </summary>
public class trashmessage : ppmessage
{}
}
}
 
 
2.  p2pserver
namespace p2p.p2pserver
{
using system;
using system.net;
using system.net.sockets;
using system.threading;
using p2p.wellknown;
/// <summary>
/// appclass 的摘要说明。
/// </summary>
public class appclass
{
public static void main()
{
server server = new server();
try
{
server.start();
console.readline();
server.stop();
}
catch
{
}
}
}
/// <summary>
/// server 的摘要说明。
/// </summary>
public class server
{
private udpclient server;
private usercollection userlist;
private thread serverthread;
private ipendpoint remotepoint;
 
public server()
{
userlist = new usercollection();
remotepoint = new ipendpoint(ipaddress.any, 0);
serverthread = new thread(new threadstart(run));
}
 
public void start()
{
try
{
server = new udpclient(p2pconsts.srv_port);
serverthread.start();
console.writeline("p2p server started, waiting client connect...");
}
catch(exception exp)
{
console.writeline("start p2p server error: " + exp.message);
throw exp;
}
}
 
public void stop()
{
console.writeline("p2p server stopping...");
try
{
serverthread.abort();
server.close();
console.writeline("stop ok.");
}
catch(exception exp)
{
console.writeline("stop error: " + exp.message);
throw exp;
}
 
}
 
private void run()
{
byte[] buffer = null;
while (true)
{
byte[] msgbuffer = server.receive(ref remotepoint);
try
{
object msgobj = formatterhelper.deserialize(msgbuffer);
type msgtype = msgobj.gettype();
if (msgtype == typeof(p2p.wellknown.c2s.loginmessage))
{
// 转换接受的消息
p2p.wellknown.c2s.loginmessage lginmsg = (p2p.wellknown.c2s.loginmessage)msgobj;
console.writeline("has an user login: {0}", lginmsg.username);
// 添加用户到列表
ipendpoint userendpoint = new ipendpoint(remotepoint.address, remotepoint.port);
user user = new user(lginmsg.username, userendpoint);
userlist.add(user);
// 发送应答消息
p2p.wellknown.s2c.getusersresponsemessage usersmsg = new p2p.wellknown.s2c.getusersresponsemessage(userlist);
buffer = formatterhelper.serialize(usersmsg);
server.send(buffer, buffer.length, remotepoint);
}
else if (msgtype == typeof(p2p.wellknown.c2s.logoutmessage))
{
// 转换接受的消息
p2p.wellknown.c2s.logoutmessage lgoutmsg = (p2p.wellknown.c2s.logoutmessage)msgobj;
console.writeline("has an user logout: {0}", lgoutmsg.username);
// 从列表中删除用户
user lgoutuser = userlist.find(lgoutmsg.username);
if (lgoutuser != null)
{
userlist.remove(lgoutuser);
}
}
else if (msgtype == typeof(p2p.wellknown.c2s.translatemessage))
{
// 转换接受的消息
p2p.wellknown.c2s.translatemessage transmsg = (p2p.wellknown.c2s.translatemessage)msgobj;
console.writeline("{0}(1) wants to p2p {2}", remotepoint.address.tostring(), transmsg.username, transmsg.tousername);
// 获取目标用户
user touser = userlist.find(transmsg.tousername);
// 转发purch hole请求消息
if (touser == null)
{
console.writeline("remote host {0} cannot be found at index server", transmsg.tousername);
}
else
{
p2p.wellknown.s2c.someonecallyoumessage transmsg = new p2p.wellknown.s2c.someonecallyoumessage(remotepoint);
buffer = formatterhelper.serialize(transmsg);
server.send(buffer, buffer.length, touser.netpoint);
}
}
else if (msgtype == typeof(p2p.wellknown.c2s.getusersmessage))
{
// 发送当前用户信息到所有登录客户
p2p.wellknown.s2c.getusersresponsemessage srvresmsg = new p2p.wellknown.s2c.getusersresponsemessage(userlist);
buffer = formatterhelper.serialize(srvresmsg);
foreach(user user in userlist)
{
server.send(buffer, buffer.length, user.netpoint);
}
}
thread.sleep(500);
}
catch{}
}
}
}
}
 
 

#8


学习

#9


mark

#10


公司上班不能用QQ和MSN,实在是无聊,就自己做了一个局域网的聊天工具。
有兴趣的朋友可以试试看。

不需要建立服务器!!!

名称:EasyMessenger
版本:2006 第2版

主要功能介绍:
 点对点私聊
 多人群聊
 自定义表情
 发送网络图片
 即时传送文件
 历史记录保存

有需要的朋友可以来信,可以自己定义需要的群组。

下载页面:
http://www.easymessenger.cn

#11


up

#12


up