C#基于TCP的客戶端服務(wù)器通信_第1頁
C#基于TCP的客戶端服務(wù)器通信_第2頁
C#基于TCP的客戶端服務(wù)器通信_第3頁
C#基于TCP的客戶端服務(wù)器通信_第4頁
C#基于TCP的客戶端服務(wù)器通信_第5頁
已閱讀5頁,還剩19頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

1、 高級網(wǎng)絡(luò)程序設(shè)計課程設(shè)計報告題 目 基于TCP的局域網(wǎng)即時消息系統(tǒng)的客戶端和服務(wù)器端的設(shè)計與實現(xiàn)學(xué) 號 姓 名 計算機網(wǎng)絡(luò)工程教研室2016年01月11 日目 錄一、課程設(shè)計內(nèi)容.2二、設(shè)計目的.2三、設(shè)計步驟.2四、具體要求. 3五、實驗代碼. 3六、實驗結(jié)果. 20七、參考文獻. 22八、實驗心得. 22一、課程設(shè)計內(nèi)容1 Winsock的啟動與終止。2 Winsock的創(chuàng)建及綁定和關(guān)閉。3 建立通信連接listen及accept和connect。4 數(shù)據(jù)的傳輸。5 簡單的客戶機/服務(wù)器之間的通信。二、設(shè)計目的1 熟悉Windows Socket的常用函數(shù)的形式和使用方法,理解數(shù)據(jù)通信的

2、過程。2 掌握如何利用C#進行TCP協(xié)議開發(fā),完成基于TCP的局域網(wǎng)即時消息系統(tǒng)的客戶端和服務(wù)器端的設(shè)計與實現(xiàn)。三、設(shè)計步驟 在TCP/IP網(wǎng)絡(luò)中兩個進程間的相互作用的主機模式是客戶機/服務(wù)器模式(Client/Server model)。該模式的建立基于以下兩點:(1)非對等作用;(2)通信完全是異步的??蛻魴C/服務(wù)器模式在操作過程中采取的是主動請示方式:1、首先服務(wù)器方要先啟動,并根據(jù)請示提供相應(yīng)服務(wù),其過程如下:(1)打開一通信通道并告知本地主機,它愿意在某一個公認地址上接收客戶請求。(2)等待客戶請求到達該端口。(3)接收到重復(fù)服務(wù)請求,處理該請求并發(fā)送應(yīng)答信號。(4)返回第二步,等待

3、另一客戶請求(5)關(guān)閉服務(wù)器。2、客戶方:(1)打開一通信通道,并連接到服務(wù)器所在主機的特定端口。(2)向服務(wù)器發(fā)送服務(wù)請求報文,等待并接收應(yīng)答;繼續(xù)提出請求(3)請求結(jié)束后關(guān)閉通信通道并終止。3、TCP連接的套接字的系統(tǒng)調(diào)用時序圖如圖2.1所示。4、TCP連接的應(yīng)用程序流程圖如圖2.2所示。圖2.1 TCP連接的套接字的系統(tǒng)調(diào)用時序圖圖2.2 TCP連接的應(yīng)用程序流程圖 四、具體要求需要有基本的雙人、多人文字聊天功能,上下線通知,在線用戶列表,點對點文件傳輸,所有的文字或文件傳輸需支持CRC-32校驗,具有出錯重傳機制;五、實驗代碼(1)客戶機:using System;using Syst

4、em.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.IO;using System.Linq;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace SocketClient public partial class Form1 : Form pub

5、lic Form1() InitializeComponent(); Socket _socketSend; private void btnStart_Click(object sender, EventArgs e) /創(chuàng)建負責(zé)通信的Socket: if (_socketSend = null | _socketSend.Connected = false) _socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.P

6、arse(txtServer.Text); IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPoint.Text); SocketAsyncEventArgs socketE = new SocketAsyncEventArgs(); socketE.Completed += socketE_Completed; socketE.RemoteEndPoint = point; try _socketSend.ConnectAsync(socketE); catch (SocketException) else ShowMsg(&

7、quot;系統(tǒng)提示:", "已經(jīng)連接到服務(wù)器:" + _socketSend.RemoteEndPoint.ToString() + "請重新連接!"); void socketE_Completed(object sender, SocketAsyncEventArgs e) Socket acceptSocket = e.ConnectSocket; if (acceptSocket = null) ShowMsg("系統(tǒng)提示:", "向" + e.RemoteEndPoint.ToString()

8、+ "的連接建立失敗!"); return; string endPoint = acceptSocket.RemoteEndPoint.ToString(); ShowMsg("系統(tǒng)提示:", "向" + endPoint + "的連接成功建立!"); while (true) /客戶端連接成功后,客戶端應(yīng)該接受服務(wù)器發(fā)來的消息 byte buffer = new byte1024 * 1024 * 2; /實際接受到的有效字節(jié)數(shù) int r = 0; try r = acceptSocket.Receive(b

9、uffer); catch (SocketException) r = 0; if (r = 0) if (acceptSocket.Connected) ShowMsg("系統(tǒng)提示:", "向" + endPoint + "的連接斷開!"); acceptSocket.Close(); break; /如果發(fā)送的數(shù)據(jù)是文字(標識 0 ) if (buffer0 = 0) string str = Encoding.UTF8.GetString(buffer, 1, r - 1); ShowMsg(endPoint + ":

10、", str); else if (buffer0 = 1) string fileName = Encoding.UTF8.GetString(buffer, 17, 1000).Trim('0'); SingleObject.GetSingle().LastSendedFile = Path.GetTempFileName(); using (FileStream fsWrite = new FileStream(SingleObject.GetSingle().LastSendedFile, FileMode.OpenOrCreate, FileAccess.W

11、rite) fsWrite.Write(buffer, 0, r); ShowMsg(endPoint + ":", "給你發(fā)送了文件:" + fileName); else if (buffer0 = 2) SingleObject.GetSingle().IsMove = true; else ShowMsg("系統(tǒng)消息:", "無法識別“" + endPoint + "”發(fā)送來的消息類型!"); private void Received() this.Activate(); privat

12、e void MoveForm() Received(); Random r = new Random(); Point location = this.Location; DateTime time = DateTime.Now; while (DateTime.Now - time) < TimeSpan.FromSeconds(1.5) Point nextPoint = new Point(location.X + r.Next(-10, 11), location.Y + r.Next(-10, 11); this.Location = nextPoint; System.Th

13、reading.Thread.Sleep(10); this.Location = location; private void btnSendMsg_Click(object sender, EventArgs e) if (_socketSend = null | _socketSend.Connected = false) ShowMsg("系統(tǒng)提示:", "請先連接服務(wù)器,再發(fā)送消息!"); return; string endPoint = _socketSend.RemoteEndPoint.ToString(); byte basicBuf

14、fer = Encoding.UTF8.GetBytes(txtMsg.Text); List<byte> list = new List<byte>(basicBuffer.Length + 1); list.Add(0); list.AddRange(basicBuffer); byte buffer = list.ToArray(); list = null; try _socketSend.Send(buffer); ShowMsg("向" + endPoint + "發(fā)送:", txtMsg.Text); catch (

15、SocketException) txtMsg.Clear(); private void ShowMsg(string sender, string msg) string time = DateTime.Now.ToString("hh:mm:ss"); SingleObject.GetSingle().LogString.AppendLine(time + " " + sender); SingleObject.GetSingle().LogString.AppendLine(msg); SingleObject.GetSingle().LogSt

16、ring.AppendLine(); private void timerChange_Tick(object sender, EventArgs e) lblTime.Text = DateTime.Now.ToString(); /txtLog的數(shù)據(jù) if (!txtLogUserChange && !(txtLog.Text = SingleObject.GetSingle().LogString.ToString() txtLogAutoChange = true; txtLog.Text = SingleObject.GetSingle().LogString.ToS

17、tring(); txtLogAutoChange = false; /是否震動 if (SingleObject.GetSingle().IsMove) MoveForm(); SingleObject.GetSingle().IsMove = false; bool txtLogUserChange = false, txtLogAutoChange = false; private void txtLog_TextChanged(object sender, EventArgs e) if (txtLogAutoChange) return; txtLogUserChange = tru

18、e; private void btnClose_Click(object sender, EventArgs e) if (_socketSend != null | _socketSend.Connected = true) ShowMsg("系統(tǒng)提示:", "服務(wù)器已經(jīng)斷開或未連接!"); return; try ShowMsg("系統(tǒng)提示:", "向" + _socketSend.RemoteEndPoint.ToString() + "的連接斷開!"); _socketSend.Clo

19、se(); catch (SocketException) private void btnMoveForm_Click(object sender, EventArgs e) if (_socketSend = null | _socketSend.Connected = false) ShowMsg("系統(tǒng)提示:", "請先連接服務(wù)器,再發(fā)送消息!"); return; string endPoint = _socketSend.RemoteEndPoint.ToString(); byte buffer = new byte1 2 ; try _s

20、ocketSend.Send(buffer); ShowMsg("向" + endPoint + "發(fā)送:", "你給對方發(fā)送了一個震動!"); catch (SocketException) MoveForm(); private void btnReceiveFile_Click(object sender, EventArgs e) if (string.IsNullOrEmpty(SingleObject.GetSingle().LastSendedFile) ShowMsg("系統(tǒng)提示:", "

21、目前沒有接收到任何的文件!"); return; byte buffer = new byte1024 * 1024 * 5 + 1024; int r; using (FileStream fsRead = new FileStream(SingleObject.GetSingle().LastSendedFile, FileMode.OpenOrCreate, FileAccess.Read) r = fsRead.Read(buffer, 0, buffer.Length); byte guidb = new byte16; for (int i = 0; i < gui

22、db.Length; i+) guidbi = bufferi + 1; Guid guid = new Guid(guidb);/buffer, 1, 16); string fileName = Encoding.UTF8.GetString(buffer, 17, 1000).Trim('0'); SaveFileDialog sfd = new SaveFileDialog(); sfd.FileName = fileName; sfd.DefaultExt = Path.GetExtension(fileName); sfd.Filter = "所有文件|*

23、.*" sfd.Title = "請選擇需要保存的路徑" if (sfd.ShowDialog() = DialogResult.OK) using (FileStream fsWrite = new FileStream(sfd.FileName, FileMode.OpenOrCreate, FileAccess.Write) fsWrite.Write(buffer, 1024, r - 1024); ShowMsg("系統(tǒng)提示:", "保存文件成功!"); private void btnSendFile_Click

24、(object sender, EventArgs e) if (_socketSend = null | _socketSend.Connected = false) ShowMsg("系統(tǒng)提示:", "請先連接服務(wù)器,再發(fā)送消息!"); return; string endPoint = _socketSend.RemoteEndPoint.ToString(); OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "所有文件|*.*" ofd.Title = "

25、;請選擇要發(fā)送的文件" ofd.CheckFileExists = true; if (ofd.ShowDialog() = DialogResult.OK) string fileName = ofd.FileName; if (File.Exists(fileName) using (FileStream fsReader = new FileStream(fileName, FileMode.Open, FileAccess.Read) byte buffer = new byte1024 * 1024 * 5 + 1024; int r = fsReader.Read(buf

26、fer, 1024, buffer.Length - 1024); if (fsReader.Length < buffer.Length - 1024) buffer0 = 1; byte nameBuffer = Encoding.UTF8.GetBytes(Path.GetFileName(fileName); if (nameBuffer.Length > 1000) return; byte guidBuffer = Guid.NewGuid().ToByteArray(); guidBuffer.CopyTo(buffer, 1); nameBuffer.CopyTo(

27、buffer, 17); try _socketSend.Send(buffer, r + 1024, SocketFlags.None); ShowMsg("向" + endPoint + "發(fā)送:", "你給對方發(fā)送了文件: " + Path.GetFileName(fileName); catch (SocketException) else ShowMsg("系統(tǒng)消息:", "所選擇的文件太大!"); else ShowMsg("系統(tǒng)消息:", "所選擇的文

28、件不存在!"); (2)服務(wù)器:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.IO;using System.Linq;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;using System.Threading.Tasks;using System.Windows

29、.Forms;namespace SocketStd public partial class Form1 : Form public Form1() InitializeComponent(); Socket _socketWatch;服務(wù)器啟動監(jiān)聽: private void btnStart_Click(object sender, EventArgs e) if (_socketWatch = null) _socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

30、 IPAddress ip = IPAddress.Any; IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPoint.Text); _socketWatch.Bind(point); _socketWatch.Listen(10); ShowMsg("系統(tǒng)提示:", "監(jiān)聽成功!"); BeginSocket(_socketWatch); else ShowMsg("系統(tǒng)提示:", "已經(jīng)開始監(jiān)聽了!"); private void BeginS

31、ocket(Socket socketWatch) SocketAsyncEventArgs sockete = new SocketAsyncEventArgs(); sockete.Completed += sockete_Completed; if (!socketWatch.AcceptAsync(sockete) if (sockete.AcceptSocket != null) CompletedSocket(sockete.AcceptSocket); / <summary> / 當連接成功時調(diào)用此方法 / </summary> / <param n

32、ame="acceptSocket">連接的Socket對象</param> private void CompletedSocket(Socket acceptSocket) BeginSocket(_socketWatch); string endPoint = acceptSocket.RemoteEndPoint.ToString(); if (SingleObject.GetSingle().ConnectedSocket.ContainsKey(endPoint) acceptSocket.Close(); ShowMsg("系統(tǒng)提示

33、:", "向" + endPoint + "的連接成功建立!"); SingleObject.GetSingle().ConnectedSocket.Add(endPoint, acceptSocket); while (true) /客戶端連接成功后,服務(wù)器應(yīng)該接受客戶端發(fā)來的消息 byte buffer = new byte1024 * 1024 * 2; /實際接受到的有效字節(jié)數(shù) int r = 0; try r = acceptSocket.Receive(buffer); catch (SocketException) r = 0;

34、if (r = 0) if (acceptSocket.Connected) ShowMsg("系統(tǒng)提示:", "向" + endPoint + "的連接斷開!"); SingleObject.GetSingle().ConnectedSocket.Remove(endPoint); acceptSocket.Close(); break; if (buffer0 = 0) string str = Encoding.UTF8.GetString(buffer, 1, r - 1); ShowMsg(endPoint + "

35、:", str); else if (buffer0 = 1) string fileName = Encoding.UTF8.GetString(buffer, 17, 1000).Trim('0'); SingleObject.GetSingle().LastSendedFile = Path.GetTempFileName(); using (FileStream fsWrite = new FileStream(SingleObject.GetSingle().LastSendedFile, FileMode.OpenOrCreate, FileAccess.

36、Write) fsWrite.Write(buffer, 0, r); ShowMsg(endPoint + ":", "給你發(fā)送了文件:" + fileName); else if (buffer0 = 2) SingleObject.GetSingle().IsMove = true; else ShowMsg("系統(tǒng)消息:", "無法識別“" + endPoint + "”發(fā)送來的消息類型!"); private void Received() this.Activate(); priva

37、te void MoveForm() Received(); Random r = new Random(); Point location = this.Location; DateTime time = DateTime.Now; while (DateTime.Now - time) < TimeSpan.FromSeconds(1.5) Point nextPoint = new Point(location.X + r.Next(-10, 11), location.Y + r.Next(-10, 11); this.Location = nextPoint; System.T

38、hreading.Thread.Sleep(10); this.Location = location; void sockete_Completed(object sender, SocketAsyncEventArgs e) CompletedSocket(e.AcceptSocket); private void ShowMsg(string sender, string msg) string time = DateTime.Now.ToString("hh:mm:ss"); SingleObject.GetSingle().LogString.AppendLine(time + " " + sender); SingleObject.GetSingle().LogString.AppendLine(msg); SingleObject.GetSingle().LogString.

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論