C#菜鸟做这个东东竟然花了快三天的时间了,真是菜,菜,菜~~~
下面是我用C#写的 一个简单的TCP通信,主要的功能有:
(1) 多个客户端与服务器间的数据交流
(2)可以实现群发的功能
(3)客户端与服务端可以进行文件的传输
主要用到的知识: TCP里的 socket 、、、 多线程 Thread 、、、
下面的是界面:


下面分别是服务端和客户端的代码,如若借用,请标明出处~~~
服务端代码:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.Net.Sockets;
- using System.Net;
- using System.Threading;
- using System.IO;
-
- namespace _11111
- {
- public partial class frm_server : Form
- {
- public frm_server()
- {
- InitializeComponent();
- TextBox.CheckForIllegalCrossThreadCalls = false;
- }
-
- Thread threadWatch = null;
- Socket socketWatch = null;
-
- Dictionary<string, Socket> dict = new Dictionary<string, Socket>();
- Dictionary<string, Thread> dictThread = new Dictionary<string, Thread>();
-
- private void btnBeginListen_Click(object sender, EventArgs e)
- {
-
- socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
-
- IPAddress address = IPAddress.Parse(txtIp.Text.Trim());
-
- IPEndPoint endPoint = new IPEndPoint(address, int.Parse(txtPort.Text.Trim()));
- try
- {
-
- socketWatch.Bind(endPoint);
- }
- catch (SocketException se)
- {
- MessageBox.Show("异常:"+se.Message);
- return;
- }
-
- socketWatch.Listen(10);
-
- threadWatch = new Thread(WatchConnecting);
- threadWatch.IsBackground = true;
- threadWatch.Start();
- ShowMsg("服务器启动监听成功!");
-
- }
-
-
-
-
- void WatchConnecting()
- {
- while (true)
- {
-
- Socket sokConnection = socketWatch.Accept();
-
- lbOnline.Items.Add(sokConnection.RemoteEndPoint.ToString());
-
- dict.Add(sokConnection.RemoteEndPoint.ToString(), sokConnection);
- ShowMsg("客户端连接成功!");
- Thread thr = new Thread(RecMsg);
- thr.IsBackground = true;
- thr.Start(sokConnection);
- dictThread.Add(sokConnection.RemoteEndPoint.ToString(), thr);
- }
- }
-
- void RecMsg(object sokConnectionparn)
- {
- Socket sokClient = sokConnectionparn as Socket;
- while (true)
- {
-
- byte[] arrMsgRec = new byte[1024 * 1024 * 2];
-
- int length = -1;
- try
- {
- length = sokClient.Receive(arrMsgRec);
- }
- catch (SocketException se)
- {
- ShowMsg("异常:" + se.Message);
-
- dict.Remove(sokClient.RemoteEndPoint.ToString());
-
- dictThread.Remove(sokClient.RemoteEndPoint.ToString());
-
- lbOnline.Items.Remove(sokClient.RemoteEndPoint.ToString());
- break;
- }
- catch (Exception e)
- {
- ShowMsg("异常:" + e.Message);
-
- dict.Remove(sokClient.RemoteEndPoint.ToString());
-
- dictThread.Remove(sokClient.RemoteEndPoint.ToString());
-
- lbOnline.Items.Remove(sokClient.RemoteEndPoint.ToString());
- break;
- }
- if (arrMsgRec[0] == 0)
- {
- string strMsg = System.Text.Encoding.UTF8.GetString(arrMsgRec,1, length-1);
- ShowMsg(strMsg);
- }
- if (arrMsgRec[0] == 1)
- {
- SaveFileDialog sfd = new SaveFileDialog();
-
- if (sfd.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
- {
-
- string fileSavePath = sfd.FileName;
-
- using (FileStream fs = new FileStream(fileSavePath, FileMode.Create))
- {
- fs.Write(arrMsgRec, 1, length - 1);
- ShowMsg("文件保存成功:" + fileSavePath);
- }
- }
- }
- }
- }
-
- void ShowMsg(string str)
- {
- txtMsg.AppendText(str + "\r\n");
- }
-
-
- private void btnSend_Click(object sender, EventArgs e)
- {
- string strMsg = "服务器" + "\r\n" + " -->" + txtMsgSend.Text.Trim() + "\r\n";
- byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(strMsg);
- byte[] arrSendMsg=new byte[arrMsg.Length+1];
- arrSendMsg[0] = 0;
- Buffer.BlockCopy(arrMsg, 0, arrSendMsg, 1, arrMsg.Length);
- string strKey = "";
- strKey = lbOnline.Text.Trim();
- if (string.IsNullOrEmpty(strKey))
- {
- MessageBox.Show("请选择你要发送的好友!!!");
- }
- else
- {
- dict[strKey].Send(arrSendMsg);
- ShowMsg(strMsg);
- txtMsgSend.Clear();
- }
- }
-
-
-
-
-
-
- private void btnSendToAll_Click(object sender, EventArgs e)
- {
- string strMsg = "服务器" + "\r\n" + " -->" + txtMsgSend.Text.Trim() + "\r\n";
- byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(strMsg);
- <span style="font-size:14px;"> byte[] arrSendMsg = new byte[arrMsg.Length + 1];
- arrSendMsg[0] = 0;
- Buffer.BlockCopy(arrMsg, 0, arrSendMsg, 1, arrMsg.Length);</span>
-
- foreach (Socket s in dict.Values)
- {
- s.Send(arrMsg);
- }
- ShowMsg(strMsg);
- txtMsgSend.Clear();
- ShowMsg(" 群发完毕~~~");
- }
-
-
- private void btnSelectFile_Click_1(object sender, EventArgs e)
- {
- OpenFileDialog ofd = new OpenFileDialog();
- ofd.InitialDirectory = "D:\\";
- if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
- {
- txtSelectFile.Text = ofd.FileName;
- }
- }
-
-
- private void btnSendFile_Click_1(object sender, EventArgs e)
- {
- if (string.IsNullOrEmpty(txtSelectFile.Text))
- {
- MessageBox.Show("请选择你要发送的文件!!!");
- }
- else
- {
-
- using (FileStream fs = new FileStream(txtSelectFile.Text, FileMode.Open))
- {
- string fileName=System.IO.Path.GetFileName(txtSelectFile.Text);
- string fileExtension=System.IO.Path.GetExtension(txtSelectFile.Text);
- string strMsg = "我给你发送的文件为: "+fileName+fileExtension+"\r\n";
- byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(strMsg);
- byte[] arrSendMsg = new byte[arrMsg.Length + 1];
- arrSendMsg[0] = 0;
- Buffer.BlockCopy(arrMsg, 0, arrSendMsg, 1, arrMsg.Length);
- bool fff = true;
- string strKey = "";
- strKey = lbOnline.Text.Trim();
- if (string.IsNullOrEmpty(strKey))
- {
- MessageBox.Show("请选择你要发送的好友!!!");
- }
- else
- {
- dict[strKey].Send(arrSendMsg);
- byte[] arrFile = new byte[1024 * 1024 * 2];
- int length = fs.Read(arrFile, 0, arrFile.Length);
- byte[] arrFileSend = new byte[length + 1];
- arrFileSend[0] = 1;
- Buffer.BlockCopy(arrFile, 0, arrFileSend, 1, length);
-
-
- dict[strKey].Send(arrFileSend);
- txtSelectFile.Clear();
- }
- }
- }
- txtSelectFile.Clear();
- }
-
- }
- }
客户端代码:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
-
- using System.Net;
- using System.Net.Sockets;
- using System.Threading;
- using System.IO;
-
- namespace _2222222
- {
- public partial class frmClient : Form
- {
- public frmClient()
- {
- InitializeComponent();
- TextBox.CheckForIllegalCrossThreadCalls = false;
- }
-
- Thread threadClient = null;
- Socket sockClient = null;
- private void btnConnect_Click(object sender, EventArgs e)
- {
- IPAddress ip = IPAddress.Parse(txtIp.Text.Trim());
- IPEndPoint endPoint=new IPEndPoint (ip,int.Parse(txtPort.Text.Trim()));
- sockClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- try
- {
- ShowMsg("与服务器连接中……");
- sockClient.Connect(endPoint);
-
- }
- catch (SocketException se)
- {
- MessageBox.Show(se.Message);
- return;
-
- }
- ShowMsg("与服务器连接成功!!!");
- threadClient = new Thread(RecMsg);
- threadClient.IsBackground = true;
- threadClient.Start();
-
- }
-
- void RecMsg()
- {
- while (true)
- {
-
- byte[] arrMsgRec = new byte[1024 * 1024 * 2];
-
- int length = -1;
- try
- {
- length = sockClient.Receive(arrMsgRec);
- }
- catch (SocketException se)
- {
- ShowMsg("异常;" + se.Message);
- return;
- }
- catch (Exception e)
- {
- ShowMsg("异常:"+e.Message);
- return;
- }
- if (arrMsgRec[0] == 0)
- {
- string strMsg = System.Text.Encoding.UTF8.GetString(arrMsgRec, 1, length-1);
- ShowMsg(strMsg);
- }
- if (arrMsgRec[0] == 1)
- {
-
- try
- {
- SaveFileDialog sfd = new SaveFileDialog();
-
- if (sfd.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
- {
-
- string fileSavePath = sfd.FileName;
-
- using (FileStream fs = new FileStream(fileSavePath, FileMode.Create))
- {
- fs.Write(arrMsgRec, 1, length - 1);
- ShowMsg("文件保存成功:" + fileSavePath);
- }
- }
- }
- catch (Exception aaa)
- {
- MessageBox.Show(aaa.Message);
- }
- }
- }
- }
- void ShowMsg(string str)
- {
- txtMsg.AppendText(str + "\r\n");
- }
-
-
- private void btnSendMsg_Click(object sender, EventArgs e)
- {
- string strMsg = txtName.Text.Trim()+"\r\n"+" -->"+ txtSendMsg.Text.Trim()+ "\r\n";
- byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(strMsg);
- byte[] arrSendMsg = new byte[arrMsg.Length + 1];
- arrSendMsg[0] = 0;
- Buffer.BlockCopy(arrMsg, 0, arrSendMsg, 1, arrMsg.Length);
- sockClient.Send(arrSendMsg);
- ShowMsg(strMsg);
- txtSendMsg.Clear();
- }
-
-
- private void btnSelectFile_Click(object sender, EventArgs e)
- {
- OpenFileDialog ofd = new OpenFileDialog();
- ofd.InitialDirectory = "D:\\";
- if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
- {
- txtSelectFile.Text = ofd.FileName;
- }
- }
-
-
- private void btnSendFile_Click(object sender, EventArgs e)
- {
- if (string.IsNullOrEmpty(txtSelectFile.Text))
- {
- MessageBox.Show("请选择要发送的文件!!!");
- }
- else
- {
-
- using (FileStream fs = new FileStream(txtSelectFile.Text, FileMode.Open))
- {
-
- string fileName = System.IO.Path.GetFileName(txtSelectFile.Text);
- string fileExtension = System.IO.Path.GetExtension(txtSelectFile.Text);
- string strMsg = "我给你发送的文件为: " + fileName + "\r\n";
- byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(strMsg);
- byte[] arrSendMsg = new byte[arrMsg.Length + 1];
- arrSendMsg[0] = 0;
- Buffer.BlockCopy(arrMsg, 0, arrSendMsg, 1, arrMsg.Length);
- sockClient.Send(arrSendMsg);
-
- byte[] arrFile = new byte[1024 * 1024 * 2];
- int length = fs.Read(arrFile, 0, arrFile.Length);
- byte[] arrFileSend = new byte[length + 1];
- arrFileSend[0] = 1;
- Buffer.BlockCopy(arrFile, 0, arrFileSend, 1, length);
-
- sockClient.Send(arrFileSend);
- txtSelectFile.Clear();
- }
- }
- }
- }
- }
- 转自http://blog.csdn.net/chwei_cson/article/details/7737766
C# TCP实现多个客户端与服务端 数据 与 文件的传输
原文:http://www.cnblogs.com/catWang/p/4081349.html