//服务器端代码例子
public TcpListener MyTcpListener;
public Socket MySocket;
public Thread MyThread;
public List <Socket > MySockets=new List<Socket>() ;
//启动服务器按钮
private void bt_Connection_Click(object sender, EventArgs e)
{
MyTcpListener = new TcpListener(5000);
MyTcpListener.Start();
label1.Text = "服务器启动成功!";
MyThread = new Thread (new ThreadStart(ListenPort));
//启动时就开始监听端口
MyThread.Start();
}
//显示聊天信息
delegate void MyDelegateForSetText(string content);
private void SetText(string content)
{
richTextBox1.Text+= content+" "+DateTime .Now .ToString ()+"\r\n";
}
//监听端口
public void ListenPort()
{
while (true)
{
MySocket = MyTcpListener.AcceptSocket();
MySockets.Add(MySocket);
//监听端口开启接受数据
Thread MyReceivedDataThread = new Thread(new ThreadStart(ReceiveData));
MyReceivedDataThread .Start ();
}
}
//接受数据
public void ReceiveData()
{
while (true)
{
//定义一个数据接收二进制流
byte[] arr = new byte[1024];
//接受数据的长度
int k = MySocket.Receive(arr);
//获取客户端发送的数据并转换成字符串
string MyString=System.Text.Encoding.Default.GetString(arr, 0, k);
//聊天内容的富文本框显示聊天内容
this.Invoke(new MyDelegateForSetText(SetText),MyString );
//将接受的一个客户端的内容向其他的客户端发送
for (int i = 0; i < MySockets.Count; i++)
{
MySockets[i].Send(System .Text .Encoding .Default .GetBytes (MyString));
}
}
}
//发送数据
private void bt_send_Click(object sender, EventArgs e)
{
byte [] arr=System .Text .Encoding .Default .GetBytes (richTextBox2 .Text );
//先显示到本地的聊天内容上
this.Invoke(new MyDelegateForSetText(SetText), System.Text.Encoding.Default.GetString(arr, 0, arr.Length));
//再向其它的客户端发送
for (int i = 0; i < MySockets.Count; i++)
{
MySockets[i].Send (System.Text .Encoding .Default .GetBytes (richTextBox2 .Text));
}
}
//客户端代码
private TcpClient MyTcpClient;
private NetworkStream MyNetworkStream;
private Thread MyThread;
//开始连接服务器
private void bt_Connection_Click(object sender, EventArgs e)
{
MyTcpClient = new TcpClient();
MyTcpClient.Connect("127.0.0.1",5000);
label1.Text = "连接成功!!";
MyNetworkStream = MyTcpClient.GetStream();
MyThread = new Thread (new ThreadStart(ReceivedData));
MyThread.Start();
}
//显示聊天内容 使用托管
delegate void MyDelegateForSetText(string content);
private void SetText(string content)
{
string str = content + " " + DateTime.Now.ToString() + "\r\n";
richTextBox1.AppendText(str);
}
//接受数据
private void ReceivedData()
{
while (true)
{
byte[] result = new byte[1024];
int k = MyNetworkStream.Read(result, 0, 1024);
this.Invoke(new MyDelegateForSetText(SetText), System.Text.Encoding.Default.GetString(result, 0, k));
}
}
//发送数据
private void bt_send_Click(object sender, EventArgs e)
{
byte[] arr = System.Text.Encoding.Default.GetBytes(richTextBox2.Text);
MyNetworkStream.Write(arr, 0, arr.Length);
}
你的这个问题,在园子里已经有一套成熟的通信框架 ESFramework通信框架,它就支持可靠的P2P通信,服务就是起的一个搭桥的作用,双方的P2P打通后,就可以进行P2P的通信了,用户发送的数据就是直接从客户端到客户端,不需要进过服务端了。建议你去参考一下,应该会给你带来帮助