logo资料库

socket在C#中的使用.doc

第1页 / 共8页
第2页 / 共8页
第3页 / 共8页
第4页 / 共8页
第5页 / 共8页
第6页 / 共8页
第7页 / 共8页
第8页 / 共8页
资料共8页,全文预览结束
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; using System.IO; using System.Net; using System.Net.Sockets; using System.Configuration; namespace ChatApp { public partial class ChatForm : Form { byte[] clientData;//存ä?放¤?文?件t数ºy据Y的Ì?字Á?节¨²数ºy组Á¨¦ TcpListener tcpListener;//文?件t监¨¤听¬y对?象¨® readonly string client_ip = ConfigurationManager.AppSettings["client_ip"]; readonly string server_ip = ConfigurationManager.AppSettings["server_ip"]; readonly int mess_port = Int32.Parse(ConfigurationManager.AppSettings["mess_port"]); readonly int file_port = Int32.Parse(ConfigurationManager.AppSettings["file_port"]); public ChatForm() { InitializeComponent(); } /// /// 窗ä¡ã口¨²加¨®载? /// /// /// private void ServerForm_Load(object sender, EventArgs e) { this.ReceiveMessage(); this.ReceiveFile(); } /// /// 关?闭À?窗ä¡ã口¨² /// /// /// private void ServerForm_FormClosed(object sender, FormClosedEventArgs e)
{ } Application.Exit(); /// /// 发¤¡é送¨ª消?息¡é /// /// /// private void btnSendMess_Click(object sender, EventArgs e) { this.SendMessage(); } /// /// 发¤¡é送¨ª文?件t /// /// /// private void btnSendFile_Click(object sender, EventArgs e) { this.SendFile(); } //发¤¡é送¨ª文?件t public void SendFile() { //完ª¨º整?路¡¤径?的Ì?文?件t名? string fileName = this.GetUserSelectFile(); //真?正y的Ì?文?件t名? string orgFileName = fileName.Substring(fileName.LastIndexOf(@"\") + 1, fileName.Length - fileName.LastIndexOf(@"\") - 1); if (fileName != string.Empty) { //将?文?件t写¡ä入¨?网ª?络?流¢¡Â TcpClient tcpClient = new TcpClient(this.server_ip, this.file_port); byte[] fileNameByte = Encoding.UTF8.GetBytes(orgFileName);//将?文?件t名?编 À¨¤码? byte[] fileData = File.ReadAllBytes(fileName);//文?件t数ºy据Y byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];// 需¨¨要°a发¤¡é送¨ª的Ì?数ºy据Y byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);//文?件t名? 的Ì?长¡è度¨¨ fileNameLen.CopyTo(clientData, 0);//文?件t名?长¡è度¨¨ fileNameByte.CopyTo(clientData, 4);//文?件t名? fileData.CopyTo(clientData, 4 + fileNameByte.Length);//文?件t数ºy据Y tcpClient.Client.BeginSend(clientData, 0, clientData.Length,
SocketFlags.None, SendFileCompleted, tcpClient); } } //发¤¡é送¨ª完ª¨º毕À?回?调Ì¡Â方¤?法¤¡§ public void SendFileCompleted(IAsyncResult ar) { TcpClient tcpClient = ar.AsyncState as TcpClient; if (tcpClient != null && tcpClient.Connected) tcpClient.Close(); } //接¨®收º?文?件t完ª¨º毕À?回?调Ì¡Â方¤?法¤¡§ public void ReceiveFileCompleted(IAsyncResult ar) { TcpClient tcpClient = ar.AsyncState as TcpClient; int bytesLen = tcpClient.Client.EndReceive(ar); int fileNameLen = BitConverter.ToInt32(clientData, 0);//获?取¨?头ª¡¤4个?字Á? 节¨²表À¨ª示º?的Ì?文?件t名?的Ì?长¡è度¨¨ string fileName = Encoding.UTF8.GetString(clientData, 4, fileNameLen);//获?取¨? 文?件t名? //使º1用®?BinaryWriter将?字Á?节¨²写¡ä入¨?文?件t BinaryWriter bWrite = new BinaryWriter(File.Open(Application.StartupPath + @"\" + fileName, FileMode.Create)); bWrite.Write(clientData, 4 + fileNameLen, bytesLen - 4 - fileNameLen); bWrite.Close(); Invoke(new UpdateDisplayDelegate(UpdateDisplay), new object[] { string.Format(" 文?件t发¤¡é送¨ª结¨¢束º?,文?件t路¡¤径?:êo{0}", Application.StartupPath + @"\" + fileName) }); //异°¨¬步?接¨®收º?连¢?接¨®请?求¨® this.tcpListener.BeginAcceptTcpClient(AcceptTcpClientCompleted, this.tcpListener); } //监¨¤听¬y文?件t接¨®收º? public void ReceiveFile() { IPAddress localAddr = IPAddress.Parse(this.client_ip); this.tcpListener = new TcpListener(localAddr, this.file_port); //开a始º?侦¨¬听¬y连¢?接¨® this.tcpListener.Start(); //异°¨¬步?接¨®收º?连¢?接¨®请?求¨® this.tcpListener.BeginAcceptTcpClient(AcceptTcpClientCompleted, tcpListener); } //连¢?接¨®完ª¨º毕À?
public void AcceptTcpClientCompleted(IAsyncResult ar) { TcpListener tcpListener = ar.AsyncState as TcpListener; TcpClient tcpClient = tcpListener.EndAcceptTcpClient(ar); //缓o冲?的Ì?字Á?节¨²流¢¡Â clientData = new byte[1024 * 1024 * 10]; tcpClient.Client.BeginReceive(clientData, 0, clientData.Length, SocketFlags.None, ReceiveFileCompleted, tcpClient);//接¨®收º?数ºy据Y Invoke(new UpdateDisplayDelegate(UpdateDisplay), new object[] { "对?方¤?开a始º? 给?你?发¤¡é送¨ª文?件t......" }); } //接¨®收º?消?息¡é private void ReceiveMessage() { //初?始º?化¡¥并¡é绑㨮定¡§本À?地Ì?的Ì?端?点Ì? UdpClient udpClient = new UdpClient(this.mess_port); udpClient.BeginReceive(ReceiveMessageCompleted, udpClient); } public void ReceiveMessageCompleted(IAsyncResult ar) { //远?程¨¬的Ì?端?点Ì? IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Any, 0); UdpClient udpClient = ar.AsyncState as UdpClient; byte[] data = udpClient.EndReceive(ar, ref remoteIpep); string revData = Encoding.UTF8.GetString(data, 0, data.Length); Invoke(new UpdateDisplayDelegate(UpdateDisplay), new object[] { "对?方¤?说¦Ì: êo" + revData }); //递ÌY归¨¦调Ì¡Â用®? udpClient.BeginReceive(ReceiveMessageCompleted, udpClient); } //发¤¡é送¨ª消?息¡é private void SendMessage() { if (txtMessage.Text.Trim().Length > 0) { UdpClient udpClient = new UdpClient(); //远?程¨¬的Ì?端?点Ì? IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Parse(this.server_ip), this.mess_port); //字Á?节¨²数ºy据Y byte[] data = Encoding.UTF8.GetBytes(txtMessage.Text.Trim());
//启?动¡¥异°¨¬步?调Ì¡Â用®? udpClient.BeginSend(data, data.Length, remoteIpep, SendMessageCompleted, udpClient); êo" + txtMessage.Text.Trim() }); Invoke(new UpdateDisplayDelegate(UpdateDisplay), new object[] { "我¨°说¦Ì: } } //发¤¡é送¨ª消?息¡é完ª¨º毕À? public void SendMessageCompleted(IAsyncResult ar) { UdpClient udpClient = ar.AsyncState as UdpClient; int result = udpClient.EndSend(ar); udpClient.Close(); } protected delegate void UpdateDisplayDelegate(string text); /// /// 更¨¹新?消?息¡é /// /// public void UpdateDisplay(string text) { if (txtHisMessages.Text.Length > 0) { txtHisMessages.Text += "\r\n"; } txtHisMessages.Text += text; } /// /// 取¨?得Ì?用®?户¡ì选?择?的Ì?文?件t /// /// 用®?户¡ì选?择?的Ì?文?件t名? public string GetUserSelectFile() { OpenFileDialog fileDialog = new OpenFileDialog(); fileDialog.InitialDirectory = Application.StartupPath; //fileDialog.Filter = "Microsoft Excel files (*.xls)|*.xls"; if (fileDialog.ShowDialog() == DialogResult.OK) { if ((fileDialog.FileName) != null) { return fileDialog.FileName;
} } return string.Empty; } } } using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; using System.IO; using System.Net; using System.Net.Sockets; using System.Configuration; namespace ChatApp { public partial class ChatForm : Form { public readonly string client_ip = "127.0.0.1"; public readonly string server_ip = ConfigurationManager.AppSettings["server"]; public readonly int mess_port = Int32.Parse(ConfigurationManager.AppSettings["mess_port"]); public ChatForm() { InitializeComponent(); } /// /// 窗ä¡ã口¨²加¨®载? /// /// ///
private void ServerForm_Load(object sender, EventArgs e) { this.ReceiveMessage(); } /// /// 关?闭À?窗ä¡ã口¨² /// /// /// private void ServerForm_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); } private void btnSendMess_Click(object sender, EventArgs e) { this.SendMessage(); } //接¨®收º?消?息¡é private void ReceiveMessage() { /*创ä¡ä建¡§终?结¨¢点Ì?(ê¡§EndPoint)ê?*/ IPAddress ip = IPAddress.Parse(this.client_ip);//把ã?ip地Ì?址¡¤字Á?符¤?串ä?转 Áa换?为aIPAddress类¤¨¤型¨ª的Ì?实º¦Ì例¤y IPEndPoint ipe = new IPEndPoint(ip, this.mess_port);//用®?指?定¡§的Ì?端?口¨² 和¨ªip初?始º?化¡¥IPEndPoint类¤¨¤的Ì?新?实º¦Ì例¤y /*创ä¡ä建¡§socket并¡é开a始º?监¨¤听¬y*/ Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创ä¡ä建¡§一°?个?socket对?象¨® s.Bind(ipe);//绑㨮定¡§EndPoint对?象¨® s.Listen(0);//开a始º?监¨¤听¬y /*接¨®受º¨¹到Ì?client连¢?接¨®,ê?为a此ä?连¢?接¨®建¡§立¢¡é新?的Ì?socket,ê? 并¡é接¨®受º¨¹信?息¡é*/ Socket socket = s.Accept();//为a新?建¡§连¢?接¨®创ä¡ä建¡§新?的Ì?socket IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, this.mess_port); while (true) { byte[] recvBytes = new byte[1024]; int bytes = socket.Receive(recvBytes, recvBytes.Length, SocketFlags.None);// 从䨮客¨ª户¡ì端?接¨®受º¨¹信?息¡é string recvStr = Encoding.UTF8.GetString(recvBytes, 0, bytes); this.UpdateDisplay("对?方¤?说¦Ì:êo" + recvStr); } }
//发¤¡é送¨ª消?息¡é private void SendMessage() { if (txtMessage.Text.Trim().Length > 0) { /*创ä¡ä建¡§终?结¨¢点Ì?EndPoint*/ IPAddress ip = IPAddress.Parse(this.server_ip); IPEndPoint ipe = new IPEndPoint(ip, this.mess_port);//把ã?ip和¨ª端?口¨²转 Áa化¡¥为aIPEndpoint实º¦Ì例¤y /*创ä¡ä建¡§socket并¡é连¢?接¨®到Ì?服¤t务?器¡Â*/ Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创ä¡ä建¡§Socket socket.Connect(ipe); /*向¨°服¤t务?器¡Â发¤¡é送¨ª信?息¡é*/ byte[] bs = Encoding.UTF8.GetBytes(txtMessage.Text.Trim());//把ã?字Á?符¤? 串ä?编À¨¤码?为a字Á?节¨² socket.Send(bs, bs.Length, SocketFlags.None);//发¤¡é送¨ª信?息¡é this.UpdateDisplay("我¨°说¦Ì:êo" + txtMessage.Text.Trim()); /*用®?完ª¨º关?闭À?socket*/ socket.Close(); } } //protected delegate void UpdateDisplayDelegate(string text); /// /// 更¨¹新?消?息¡é /// /// public void UpdateDisplay(string text) { if (txtHisMessages.Text.Length > 0) { txtHisMessages.Text += "\r\n"; } txtHisMessages.Text += text; } private void txtHisMessages_TextChanged(object sender, EventArgs e) { } } }
分享到:
收藏