C# Socket发送接收文件,消息

xfpengyu 贡献于2013-10-24

作者 PENG Guojin  创建于2013-10-24 06:06:00   修改者PENG Guojin  修改于2013-10-24 06:17:00字数14438

文档摘要:C# Socket发送接收文件,消息
关键词:

 C# Socket 发送接收文件,消息 l Server端 ImServer.cs 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.IO; using System.Net; namespace imserver { public partial class ImServer : Form { private Socket listener = null; private int port = 8089; private IPEndPoint listenEP = null; //所有用户 List userTable = new List(); public ImServer() { InitializeComponent(); listenEP = new IPEndPoint(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address,port); } private void ImServer_Load(object sender, EventArgs e) { listener = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listener.Bind(listenEP); listener.Listen(-1); listener.BeginAccept( new AsyncCallback(AcceptCallback), null); PrintStatus(string.Format("监听已开启{0}", listener.LocalEndPoint.ToString())); } //有用户连接调用 private void AcceptCallback(IAsyncResult iar) { try { Socket remoteClient = listener.EndAccept(iar);//当前socket string u = remoteClient.RemoteEndPoint.ToString();//ip:端口作为用户名 TransferHandler transferHandler = new TransferHandler(remoteClient); transferHandler.ReceivedMessage += new ReceivedMessageHandler(transferHandler_Received);//发送消息处理 //加入用户 userTable.Add(transferHandler); addUser(u+"\n"); //加入list PrintStatus(string.Format("{0}已连接至本地", u));//状态 //获取消息 transferHandler.BeginReceive(); } catch (Exception err) { PrintStatus(err.Message); return; } } //消息 void transferHandler_Received(StringBuilder strbu) { PrintStatus(strbu.ToString()); } //下发文件 private void sendFile_Click(object sender, EventArgs e) { for (int i = 0; i < userTable.Count;i++ ) { userTable.ElementAt(i).SendFile("C:\\System32.cab"); } PrintStatus("下发成功"); } //下发消息 private void sendMessage_Click(object sender, EventArgs e) { for (int i = 0; i < userTable.Count; i++) { userTable.ElementAt(i).Send(txtMessage.Text); } } //状态 private void PrintStatus(string msg) { BeginInvoke((MethodInvoker)delegate() { labMessage.Text = msg; }); } //加入用户列表 private void addUser(string u) { BeginInvoke((MethodInvoker)delegate() { userList.AppendText(u); }); } } } ImServer.Designer.cs namespace imserver { partial class ImServer { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.sendFile = new System.Windows.Forms.Button(); this.txtMessage = new System.Windows.Forms.TextBox(); this.userList = new System.Windows.Forms.TextBox(); this.sendMessage = new System.Windows.Forms.Button(); this.labMessage = new System.Windows.Forms.Label(); this.SuspendLayout(); // // sendFile // this.sendFile.Location = new System.Drawing.Point(214, 206); this.sendFile.Name = "sendFile"; this.sendFile.Size = new System.Drawing.Size(75, 23); this.sendFile.TabIndex = 0; this.sendFile.Text = "下发数据"; this.sendFile.UseVisualStyleBackColor = true; this.sendFile.Click += new System.EventHandler(this.sendFile_Click); // // txtMessage // this.txtMessage.Location = new System.Drawing.Point(12, 29); this.txtMessage.Multiline = true; this.txtMessage.Name = "txtMessage"; this.txtMessage.Size = new System.Drawing.Size(144, 158); this.txtMessage.TabIndex = 1; // // userList // this.userList.Enabled = false; this.userList.Location = new System.Drawing.Point(187, 29); this.userList.Multiline = true; this.userList.Name = "userList"; this.userList.Size = new System.Drawing.Size(145, 158); this.userList.TabIndex = 2; // // sendMessage // this.sendMessage.Location = new System.Drawing.Point(47, 206); this.sendMessage.Name = "sendMessage"; this.sendMessage.Size = new System.Drawing.Size(75, 23); this.sendMessage.TabIndex = 3; this.sendMessage.Text = "发送消息"; this.sendMessage.UseVisualStyleBackColor = true; this.sendMessage.Click += new System.EventHandler(this.sendMessage_Click); // // labMessage // this.labMessage.Location = new System.Drawing.Point(19, 240); this.labMessage.Name = "labMessage"; this.labMessage.Size = new System.Drawing.Size(313, 33); this.labMessage.TabIndex = 4; // // ImServer // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(344, 282); this.Controls.Add(this.labMessage); this.Controls.Add(this.sendMessage); this.Controls.Add(this.userList); this.Controls.Add(this.txtMessage); this.Controls.Add(this.sendFile); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.Name = "ImServer"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.Text = "服务端"; this.Load += new System.EventHandler(this.ImServer_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button sendFile; private System.Windows.Forms.TextBox txtMessage; private System.Windows.Forms.TextBox userList; private System.Windows.Forms.Button sendMessage; private System.Windows.Forms.Label labMessage; } } TransferHandler.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Drawing; using System.IO; namespace imserver { public delegate void ReceivedFileHandler(MemoryStream ms);//文件 public delegate void ReceivedMessageHandler(StringBuilder strbu);//消息 /*处理下发,接收*/ public class TransferHandler { private Socket _client = null; public event ReceivedFileHandler ReceivedFile; //文件 public event ReceivedMessageHandler ReceivedMessage; //消息 public TransferHandler(Socket client) { _client = client; } public void BeginReceive() { byte[] buffer = new byte[8]; //由于long占8位字节,所以先获取前8位字节数据 IAsyncResult iar = _client.BeginReceive( buffer, 0, buffer.Length, SocketFlags.None, null, null); int len = _client.EndReceive(iar); int offset = 0; int length = BitConverter.ToInt32(buffer, offset); //先获取文件长度 Receive(length); //取数据 BeginReceive(); //继续接收 } //取数据 private void Receive(long filelen) { StringBuilder str = new StringBuilder();//存放message MemoryStream ms = new MemoryStream();//存放file int bytesRead = 0;//存放真实读取的大小 long count = 0;//已取总大小 byte[] buffer = new byte[8192];//零时byte Boolean isfile = true;//是否为文件 //判断是否有前缀 if (filelen > 9) { byte[] type = new byte[9]; _client.Receive(type, type.Length, SocketFlags.None); //读取前9位 //判断是否为message if ("[message]".Equals(System.Text.Encoding.Default.GetString(type).TrimEnd())) { isfile = false; } //是文件要把刚去取的type放入ms if (isfile) { ms.Write(type, 0, type.Length); } count += 9;//加上已取大小 } //是否取完 while (count != filelen) { bytesRead = _client.Receive(buffer, buffer.Length, SocketFlags.None); if (isfile) { ms.Write(buffer, 0, bytesRead);//放入ms } else { str.Append(System.Text.Encoding.Default.GetString(buffer).TrimEnd()); //放入str } count += bytesRead;//叠加已取大小 } //处理显示 if (isfile) { ReceivedFile(ms); } else { ReceivedMessage(str); } } /* * 发送消息 */ public void Send(string message) { byte[] byteArray = System.Text.Encoding.Default.GetBytes("[message]"+message); //消息长度 byte[] len = BitConverter.GetBytes(byteArray.Length); //temp = len + byteArray byte[] temp = new byte[byteArray.Length + 8]; for (int i = 0; i < len.Length; i++) { temp[i] = len[i]; } for (int i = 8; i < temp.Length; i++) { temp[i] = byteArray[i - 8]; } _client.BeginSend(temp, 0, temp.Length, SocketFlags.None, new AsyncCallback(SendCallback), null); } /*结束*/ private void SendCallback(IAsyncResult iar) { _client.EndSend(iar); } //发送文件 public void SendFile(string filename) { FileInfo fi = new FileInfo(filename); byte[] len = BitConverter.GetBytes(fi.Length); //首先把文件长度发送过去 _client.BeginSendFile(filename, len, null, TransmitFileOptions.UseDefaultWorkerThread, new AsyncCallback(SendFileCallback), null); } //文件结束 private void SendFileCallback(IAsyncResult iar) { _client.EndSendFile(iar); } } } l Client端 ImClient.cs 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.IO; namespace imClient { public partial class ImClient : Form { private Socket client = null; private int port = 8089; private IPEndPoint serverEP = null; private TransferHandler transferHandler = null; public ImClient() { InitializeComponent(); } //连接 private void btnConn_Click(object sender, EventArgs e) { ConnectServer("172.31.212.29");//连接ip this.btnConn.Enabled = false; this.sendMessage.Enabled = true; } //连接 private void ConnectServer(string serverIP) { serverEP = new IPEndPoint( IPAddress.Parse(serverIP), port); //建立socket client = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.BeginConnect(serverEP, new AsyncCallback(ConnectCallback), null); } //连接成功 private void ConnectCallback(IAsyncResult iar) { try { client.EndConnect(iar); PrintStatus("已连接至服务器。"); transferHandler = new TransferHandler(client); transferHandler.ReceivedFile += new ReceivedFileHandler(transferHandler_Received);//发送文件处理 transferHandler.ReceivedMessage += new ReceivedMessageHandler(transferHandler_Received);//发送消息处理 transferHandler.BeginReceive(); } catch (Exception err) { PrintStatus(err.Message);//error return; } } //建立文件 void transferHandler_Received(MemoryStream ms) { using (FileStream dumpFile = new FileStream(string.Format("c:\\System32{0}.cab", ms.Length), FileMode.Create, FileAccess.ReadWrite)) { ms.WriteTo(dumpFile);//保存 dumpFile.Close(); } PrintStatus(string.Format("c:\\System32{0}.cab保存成功", ms.Length)); } //显示消息 void transferHandler_Received(StringBuilder strbu) { PrintStatus(strbu.ToString()); } //显示状态 private void PrintStatus(string msg) { BeginInvoke((MethodInvoker)delegate() { labMessage.Text = msg; }); } //发送消息 private void sendMessage_Click(object sender, EventArgs e) { transferHandler.Send(this.txtMessage.Text); } } } ImClient.Designer.cs namespace imClient { partial class ImClient { /// /// Required designer variable. /// private System.ComponentModel.IContainer components = null; /// /// Clean up any resources being used. /// /// true if managed resources should be disposed; otherwise, false. protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.sendMessage = new System.Windows.Forms.Button(); this.txtMessage = new System.Windows.Forms.TextBox(); this.btnConn = new System.Windows.Forms.Button(); this.labMessage = new System.Windows.Forms.Label(); this.SuspendLayout(); // // sendMessage // this.sendMessage.Enabled = false; this.sendMessage.Location = new System.Drawing.Point(204, 187); this.sendMessage.Name = "sendMessage"; this.sendMessage.Size = new System.Drawing.Size(75, 23); this.sendMessage.TabIndex = 0; this.sendMessage.Text = "发送消息"; this.sendMessage.UseVisualStyleBackColor = true; this.sendMessage.Click += new System.EventHandler(this.sendMessage_Click); // // txtMessage // this.txtMessage.Location = new System.Drawing.Point(13, 12); this.txtMessage.Multiline = true; this.txtMessage.Name = "txtMessage"; this.txtMessage.Size = new System.Drawing.Size(311, 149); this.txtMessage.TabIndex = 1; // // btnConn // this.btnConn.Location = new System.Drawing.Point(57, 187); this.btnConn.Name = "btnConn"; this.btnConn.Size = new System.Drawing.Size(75, 23); this.btnConn.TabIndex = 2; this.btnConn.Text = "连接服务"; this.btnConn.UseVisualStyleBackColor = true; this.btnConn.Click += new System.EventHandler(this.btnConn_Click); // // labMessage // this.labMessage.Location = new System.Drawing.Point(22, 228); this.labMessage.Name = "labMessage"; this.labMessage.Size = new System.Drawing.Size(300, 35); this.labMessage.TabIndex = 3; // // ImClient // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(334, 272); this.Controls.Add(this.labMessage); this.Controls.Add(this.btnConn); this.Controls.Add(this.txtMessage); this.Controls.Add(this.sendMessage); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.Name = "ImClient"; this.Text = "客户端"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button sendMessage; private System.Windows.Forms.TextBox txtMessage; private System.Windows.Forms.Button btnConn; private System.Windows.Forms.Label labMessage; } } TransferHandler.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Drawing; using System.IO; namespace imClient { public delegate void ReceivedFileHandler(MemoryStream ms);//文件 public delegate void ReceivedMessageHandler(StringBuilder strbu);//消息 /*处理下发,接收*/ public class TransferHandler { private Socket _client = null; public event ReceivedFileHandler ReceivedFile; //文件 public event ReceivedMessageHandler ReceivedMessage; //消息 public TransferHandler(Socket client) { _client = client; } public void BeginReceive() { byte[] buffer = new byte[8]; //由于long占8位字节,所以先获取前8位字节数据 IAsyncResult iar = _client.BeginReceive( buffer, 0, buffer.Length, SocketFlags.None, null, null); int len = _client.EndReceive(iar); int offset = 0; int length = BitConverter.ToInt32(buffer, offset); //先获取文件长度 Receive(length); //取数据 BeginReceive(); //继续接收 } //取数据 private void Receive(long filelen) { StringBuilder str = new StringBuilder();//存放message MemoryStream ms = new MemoryStream();//存放file int bytesRead = 0;//存放真实读取的大小 long count = 0;//已取总大小 byte[] buffer = new byte[8192];//零时byte Boolean isfile = true;//是否为文件 //判断是否有前缀 if (filelen > 9) { byte[] type = new byte[9]; _client.Receive(type, type.Length, SocketFlags.None); //读取前9位 //判断是否为message if ("[message]".Equals(System.Text.Encoding.Default.GetString(type).TrimEnd())) { isfile = false; } //是文件要把刚去取的type放入ms if (isfile) { ms.Write(type, 0, type.Length); } count += 9;//加上已取大小 } //是否取完 while (count != filelen) { bytesRead = _client.Receive(buffer, buffer.Length, SocketFlags.None); if (isfile) { ms.Write(buffer, 0, bytesRead);//放入ms } else { str.Append(System.Text.Encoding.Default.GetString(buffer).TrimEnd()); //放入str } count += bytesRead;//叠加已取大小 } //处理显示 if (isfile) { ReceivedFile(ms); } else { ReceivedMessage(str); } } /* * 发送消息 */ public void Send(string message) { byte[] byteArray = System.Text.Encoding.Default.GetBytes("[message]"+message); //消息长度 byte[] len = BitConverter.GetBytes(byteArray.Length); //temp = len + byteArray byte[] temp = new byte[byteArray.Length + 8]; for (int i = 0; i < len.Length; i++) { temp[i] = len[i]; } for (int i = 8; i < temp.Length; i++) { temp[i] = byteArray[i - 8]; } _client.BeginSend(temp, 0, temp.Length, SocketFlags.None, new AsyncCallback(SendCallback), null); } /*结束*/ private void SendCallback(IAsyncResult iar) { _client.EndSend(iar); } //发送文件 public void SendFile(string filename) { FileInfo fi = new FileInfo(filename); byte[] len = BitConverter.GetBytes(fi.Length); //首先把文件长度发送过去 _client.BeginSendFile(filename, len, null, TransmitFileOptions.UseDefaultWorkerThread, new AsyncCallback(SendFileCallback), null); } //文件结束 private void SendFileCallback(IAsyncResult iar) { _client.EndSendFile(iar); } } }

下载文档到电脑,查找使用更方便

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 3 金币 [ 分享文档获得金币 ] 0 人已下载

下载文档