




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)
文檔簡介
1、精選優(yōu)質(zhì)文檔-傾情為你奉上精選優(yōu)質(zhì)文檔-傾情為你奉上專心-專注-專業(yè)專心-專注-專業(yè)精選優(yōu)質(zhì)文檔-傾情為你奉上專心-專注-專業(yè)局域網(wǎng)內(nèi)的tcp傳輸剛學(xué)了C#的tcp傳輸,借鑒了以前前輩的一些做法,寫了一個簡單的局域網(wǎng)內(nèi)的聊天傳文件的小軟件,界面如下:本程序需要同時在兩個能夠正常通信的處于同一局域網(wǎng)的電腦上同時開啟才能正常使用。不分主機和客戶端。(不過需要將相應(yīng)的端口號做些改動,即將以下代碼remoteendpoint =newIPEndPoint(IPAddress.Parse(textBox2.Text),3000)改為remoteendpoint = new IPEndPoint(IPAd
2、dress.Parse(textBox2.Text),2000),fileremoteendpoint= new IPEndPoint(IPAddress.Parse(textBox2.Text),5000)改為fileremoteendpoint= new IPEndPoint(IPAddress.Parse(textBox2.Text),4000);)如果在一臺電腦上測試:只需將程序復(fù)制兩份,同時打開。將復(fù)制的部分代碼做以下改變(localendpoint = new IPEndPoint(ip0,2000)改為localendpoint = new IPEndPoint(ip0,3000
3、),filelocalendpoint = new IPEndPoint(ip0, 4000)改為filelocalendpoint = new IPEndPoint(ip0, 5000),remoteendpoint =newIPEndPoint(IPAddress.Parse(textBox2.Text),3000)改為remoteendpoint = new IPEndPoint(IPAddress.Parse(textBox2.Text),2000),fileremoteendpoint= new IPEndPoint(IPAddress.Parse(textBox2.Text),50
4、00)改為fileremoteendpoint= new IPEndPoint(IPAddress.Parse(textBox2.Text),4000))以下是本程序的執(zhí)行界面:以下分別是本程序在兩臺機器上建立連接后,能正常通信的一些界面(是在自己的電腦上測試的,所以兩端的IP是一樣的):本程序只能在局域網(wǎng)內(nèi)進行通信,若要與外網(wǎng)通信,需要將代碼進行擴充,有興趣的朋友可以嘗試一下。using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Draw
5、ing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Net;using System.Net.Sockets;using System.IO;using System.Threading;namespace 簡單的文件傳輸程序 public partial class Form1 : Form IPAddress ip; int length; TcpListener tcplistener; TcpListener filetcplistener; Socket sendsocket;
6、 Socket receivesocket; Socket filereceivesocket; Socket filesendsocket; AsyncCallback callback; AsyncCallback filecallback; IPEndPoint localendpoint; IPEndPoint remoteendpoint; IPEndPoint filelocalendpoint; IPEndPoint fileremoteendpoint; Thread th=new Thread4; string requestmessage; string receivest
7、ring; string responsemessage; string filereceivestring; string filestringtosend; string title; string iptemp; string counteripstring; string filepath; string filename; string savedfilepath; string startstring; delegate void showmessage(string str); delegate void resume(); delegate void show(); byte
8、bytestosend; byte bytesreceived= new byte8192; byte filebytestosend; byte filebytesreceived = new byte32768; long sendfilelength; long receivedfilelength; int receivedlengthtemp; int sendlengthtemp; long temp = 0; long temp2 = 0; public Form1() InitializeComponent(); try string str = Dns.GetHostName
9、(); ip = Dns.GetHostAddresses(str); /用來傳送文本的本地網(wǎng)絡(luò)端點 localendpoint = new IPEndPoint(ip0,2000); /用來傳送文件的本地網(wǎng)絡(luò)端點 filelocalendpoint = new IPEndPoint(ip0, 4000); callback = new AsyncCallback(startreceivesocket); filecallback = new AsyncCallback(startfilereceivesocket); tcplistener = new TcpListener(localen
10、dpoint); filetcplistener = new TcpListener(filelocalendpoint); this.textBox1.AppendText(請選擇監(jiān)聽或者主動連接!rn請確保對方處于監(jiān)聽狀態(tài)才可發(fā)出連接申請!rn否則需重啟這個程序!n); catch (Exception ex) MessageBox.Show(ex.Message); /監(jiān)聽的時候打開 private void openth0() th0 = new Thread(new ThreadStart(th0process); th0.IsBackground = true; if (th0.I
11、sAlive = false) th0.Start(); /連接的時候打開 private void openth1() th1 = new Thread(new ThreadStart(th1process); th1.IsBackground = true; if (th1.IsAlive = false) th1.Start(); / / 將對方發(fā)過來的信息顯示到文本框 / / private void showmessagetotextbox1(string str) if (str = 已建立連接!) this.Text = str; if(str.Length9) if (str.
12、Substring(0,9)= 對方斷開了當(dāng)前連接) this.Text = 連接斷開!; if (str = 對方接受了您的連接請求!) this.button4.Enabled = false; this.button8.Enabled = false; this.textBox2.Enabled = false; this.button6.Enabled = true; this.button1.Enabled = true; this.button7.Enabled =true; this.textBox3.Enabled =true; this.button5.Enabled = t
13、rue; if (str.Substring(0, 2) = IP) iptemp = str.Substring(5, str.Length - 5); counteripstring = iptemp.Substring(0, iptemp.Length - 14); this.button4.Text = 接受; this.button6.Text = 拒絕; this.textBox2.Enabled = false; this.button4.Enabled = true; this.button6.Enabled = true; if(str.Length8) if (str.Su
14、bstring(0, 8) = 對方向您傳送文件) this.button1.Enabled = false; this.button2.Text = 接受; this.button3.Text=拒絕; this.button2.Enabled = true; this.button3.Enabled = true; if (str = 對方接受了您的傳文件請求!) th2 = new Thread(new ThreadStart(transferfile); th2.Start(); this.textBox1.AppendText(str); this.textBox1.AppendTex
15、t(rnrn); /接受對方傳過來的文件時彈出的對話框 private void showdialog() if (saveFileDialog1.ShowDialog() = DialogResult.OK) savedfilepath = saveFileDialog1.FileName; /聽方,等待被連接的那一方的監(jiān)聽程序 private void th0process() while(true) try if (receivesocket != null) receivesocket.Blocking = true; length = receivesocket.Receive(by
16、tesreceived, bytesreceived.Length, 0); receivestring = System.Text.Encoding.GetEncoding(GB2312).GetString(bytesreceived, 0, length); this.Invoke(new showmessage(showmessagetotextbox1), new object receivestring ); /這里直接用賦值語句不行,因為這里是另外開的線程 /不是主線程,所以不能直接對form上的控件直接進行訪問 if (receivestring.Length 9) if (r
17、eceivestring.Substring(0, 9) = 對方斷開了當(dāng)前連接) this.Invoke(new resume(resumefunction); closefunction(); if (receivestring.Length 12) if (receivestring.Substring(0,12)= 對方取消了發(fā)送文件的請求) this.Invoke(new resume(resumefilefunction); closefilefunction(); if (receivestring = 對方拒絕了您傳送文件的請求!) this.Invoke(new resume
18、(resumefilefunction); closefilefunction(); catch(Exception ex) MessageBox.Show(ex.Message); /發(fā)方,主動連接的那一方的監(jiān)聽程序 private void th1process() while(true) try if(sendsocket != null) sendsocket.Blocking = true; length = sendsocket.Receive(bytesreceived, bytesreceived.Length, 0); receivestring = System.Text.
19、Encoding.GetEncoding(GB2312).GetString(bytesreceived, 0, length); this.Invoke(new showmessage(showmessagetotextbox1), new object receivestring ); if (receivestring.Length 9) if (receivestring.Substring(0, 9) = 對方斷開了當(dāng)前連接) this.Invoke(new resume(resumefunction); closefunction(); if (receivestring.Leng
20、th 12) if (receivestring.Substring(0,12)= 對方取消了發(fā)送文件的請求) this.Invoke(new resume(resumefilefunction); closefilefunction(); if (receivestring = 對方拒絕了您的連接請求!) closefunction(); if (receivestring = 對方拒絕了您傳送文件的請求!) this.Invoke(new resume(resumefilefunction); closefilefunction(); catch(Exception ex) Message
21、Box.Show(ex.Message); /傳文件時,主動發(fā)送文件的一方的傳文件程序 private void transferfile() try /這里每次發(fā)之前都要受到一個對方發(fā)過來的信號是為了保證收發(fā)同步 if (filereceivesocket != null) if (filereceivesocket.Connected) /先發(fā)送文件名稱,以便在保存時有文件的原始名字 filebytestosend = new bytefilename.Length; filebytestosend = Encoding.Unicode.GetBytes(filename); filere
22、ceivesocket.Send(filebytestosend, filebytestosend.Length, 0); /隨后發(fā)送文件的長度,以便后面確定切發(fā)送的次數(shù) filereceivesocket.Blocking = true; length = filereceivesocket.Receive(filebytesreceived, filebytesreceived.Length, 0); startstring = Encoding.Unicode.GetString(filebytesreceived, 0, length); if (startstring = 下面是長度
23、) FileInfo filetosend = new FileInfo(filepath); sendfilelength = filetosend.Length; filebytestosend = new bytesendfilelength.ToString().Length; filebytestosend = Encoding.Unicode.GetBytes(sendfilelength.ToString(); filereceivesocket.Send(filebytestosend, filebytestosend.Length, 0); /最后發(fā)送文件本身的內(nèi)容 file
24、receivesocket.Blocking = true; length = filereceivesocket.Receive(filebytesreceived, filebytesreceived.Length, 0); startstring = Encoding.Unicode.GetString(filebytesreceived, 0, length); if (startstring = 開始) FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); filebytestosend =
25、 new byte32768; /這里顯示進度條 this.Invoke(new resume(sendprogressbar); /timer是主窗體上的控件,線程間不能操作 temp = 0; /這里每次temp都要清零,否則會留下上次傳輸數(shù)據(jù)的長度的痕跡 this.Invoke(new MethodInvoker(this.timer1.Start); while (temp 0 & temp sendfilelength) this.timer1.Stop(); MessageBox.Show(文件在傳輸過程中遇到錯誤!); /傳文件時,接收文件的一方的接受文件程序 private v
26、oid receivefile() try if (filesendsocket != null) if (filesendsocket.Connected) filesendsocket.Blocking = true; length = filesendsocket.Receive(filebytesreceived, filebytesreceived.Length, 0); filereceivestring=Encoding.Unicode.GetString(filebytesreceived,0,length); /接收從對方穿過來的文件的原有的文件名 saveFileDialo
27、g1.Title = 另存為; saveFileDialog1.FileName = filereceivestring; /顯示“另存為”對話框 this.Invoke(new show(showdialog); filestringtosend = 下面是長度; /這是隨意發(fā)送的一個信號,主要是為了收發(fā)同步,以免這邊還沒有接收完那邊全發(fā)送了 sendfilefunction(filestringtosend); length = filesendsocket.Receive(filebytesreceived, filebytesreceived.Length, 0); filerecei
28、vestring = Encoding.Unicode.GetString(filebytesreceived,0,length); /獲取傳送的文件的長度 receivedfilelength = long.Parse(filereceivestring); /將數(shù)字的字符串表示形式轉(zhuǎn)換為它的等效 64 位有符號整數(shù)。 filestringtosend = 開始; /這也是隨意發(fā)送的一個記號,為收發(fā)同步 sendfilefunction(filestringtosend); FileStream fs = new FileStream(savedfilepath, FileMode.Crea
29、te, FileAccess.Write); /這里顯示進度條 this.Invoke(new resume(receivedprogressbar); temp2 = 0; /這里每次temp2都要清零,否則會留下上次收到數(shù)據(jù)的長度的痕跡 this.Invoke(new MethodInvoker(this.timer2.Start); /下面是接收文件的具體內(nèi)容 while (temp2 0 & temp2receivedfilelength) this.timer2.Stop(); MessageBox.Show(文件在傳輸過程中遇到錯誤!); /顯示發(fā)方的進度條和標(biāo)簽 private
30、void sendprogressbar() progressBar1.Visible = true; progressBar1.Maximum = (int)sendfilelength; this.label2.Visible = true; /及時的更改發(fā)方當(dāng)前的進度條的值 private void sendprogressbar1() gressBar1.Value = (int)temp; /顯示收方的進度條和標(biāo)簽 private void receivedprogressbar() progressBar1.Visible = true; progressBar1.Maximum
31、= (int)receivedfilelength; this.label2.Visible = true; /及時的更改收方當(dāng)前的進度條的值 private void receivedprogressbar1() gressBar1.Value = (int)temp2; /向?qū)Ψ桨l(fā)送文本消息 private void sendfunction(string str) bytestosend = new bytestr.Length; bytestosend = System.Text.Encoding.GetEncoding(GB2312).GetBytes(str); if (recei
32、vesocket != null) if(receivesocket.Connected) receivesocket.Send(bytestosend, bytestosend.Length, 0); if (sendsocket != null) if(sendsocket.Connected) sendsocket.Send(bytestosend, bytestosend.Length, 0); /接收文件方向發(fā)方發(fā)送消息,以便同步 private void sendfilefunction(string str) filebytestosend = new bytestr.Lengt
33、h; filebytestosend = Encoding.Unicode.GetBytes(str); filesendsocket.Send(filebytestosend, filebytestosend.Length, 0); / /這要運行到beginacceptsocket函數(shù)時,就會開辟這個線程 /一直等到有對方發(fā)出連接請求來,否則這個線程一直在后臺運行 /所以有時監(jiān)聽然后復(fù)位后,這個監(jiān)聽線程還是在運行, /以至于復(fù)位后選擇主動連接,這個線程仍然在運行, /以至于后續(xù)操作中有tcplistener.stop()會引發(fā)這里的異常 / / private void startrece
34、ivesocket(IAsyncResult ar) try receivesocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); /如果后面再加一個begin,這個一直在后臺等待被連接?(得再想想) receivesocket = tcplistener.EndAcceptSocket(ar); openth0(); /聽方,等待被連接的那一方的監(jiān)聽線程 /tcplistener.BeginAcceptSocket(callback, null); /這里的最后一句注釋與不注釋
35、,有沒有區(qū)別? catch (Exception) finally System.Threading.Thread.CurrentThread.Abort(); /這是等待對方接受傳送文件申請時一直在后臺等待應(yīng)答的線程 private void startfilereceivesocket(IAsyncResult ar) try filereceivesocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); filereceivesocket = filetcplistener.
36、EndAcceptSocket(ar); catch (Exception) finally System.Threading.Thread.CurrentThread.Abort(); /關(guān)閉用于發(fā)送、接收信息的套接字和線程 private void closefunction() if (sendsocket != null) if (sendsocket.Connected = true) sendsocket.Close(); sendsocket = null; if (receivesocket != null) if (receivesocket.Connected = true
37、) receivesocket.Close(); receivesocket = null; if (th0 != null) if (th0.IsAlive = true) th0.Abort(); th0 = null; if (th1 != null) if (th1.IsAlive = true) th1.Abort(); th1 = null; /關(guān)閉用于發(fā)送、接收文件的套接字和線程 private void closefilefunction() if (filesendsocket!= null) if (filesendsocket.Connected = true) file
38、sendsocket.Close(); filesendsocket = null; if (filereceivesocket != null) if (filereceivesocket.Connected = true) filereceivesocket.Close(); filereceivesocket = null; if (th2 != null) if (th2.IsAlive = true) th2.Abort(); th2 = null; if (th3 != null) if (th3.IsAlive = true) th3.Abort(); th3 = null; /
39、斷開連接等操作后恢復(fù)到程序剛開始打開時的狀態(tài) private void resumefunction() this.textBox2.Enabled = true; this.textBox2.Clear(); this.button4.Enabled = true; this.button4.Text = 連接; this.button6.Enabled = false; this.button6.Text = 斷開連接; this.button8.Enabled = true; this.button8.Text = 監(jiān)聽; this.Text = 文件傳輸; this.button1.E
40、nabled = false; this.button7.Enabled = false; this.textBox3.Enabled = false; this.textBox3.Clear(); this.button5.Enabled = false; /斷開文件傳輸?shù)炔僮骱蠡謴?fù)到一般發(fā)送信息的狀態(tài) private void resumefilefunction() this.button1.Enabled = true; this.button2.Text = 發(fā)送; this.button2.Enabled=false; this.button3.Text = 接收; this.bu
41、tton3.Enabled=false; this.label2.Visible = false; gressBar1.Visible = false; /選擇文件按鈕觸發(fā)的事件 private void button1_Click(object sender, EventArgs e) this.openFileDialog1.InitialDirectory = c:; if (this.openFileDialog1.ShowDialog() = DialogResult.OK) filepath = this.openFileDialog1.FileName; MessageBox.S
42、how(文件未發(fā)送,請按發(fā)送鍵發(fā)送您選擇的文件!); filename = System.IO.Path.GetFileName(filepath); this.button2.Enabled = true; else MessageBox.Show(未選中文件,請重新選擇!); /發(fā)送或接受按鈕觸發(fā)的事件 private void button2_Click(object sender, EventArgs e) try if (Button)sender).Text = 發(fā)送) sendfunction(對方向您傳送文件 + filename + ,您接受嗎?); filetcpliste
43、ner.Start(); filetcplistener.BeginAcceptSocket(filecallback, null); this.textBox1.AppendText(您發(fā)送了文件!n); this.button3.Text = 取消; this.button3.Enabled=true; this.button1.Enabled = false; this.button2.Enabled = false; if (Button)sender).Text = 接受) fileremoteendpoint= new IPEndPoint(IPAddress.Parse(text
44、Box2.Text),5000); filesendsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); filesendsocket.Connect(fileremoteendpoint); this.textBox1.AppendText(您接受了對方傳文件的請求!n); sendfunction(對方接受了您的傳文件請求!); th3 = new Thread(new ThreadStart(receivefile); th3.Start(); this.button3.
45、Text = 取消; this.button2.Enabled = false; catch (Exception ex) MessageBox.Show(ex.Message); /接收按鈕觸發(fā)的事件 private void button3_Click(object sender, EventArgs e) try if (Button)sender).Text = 取消) filetcplistener.Stop(); sendfunction(對方取消了發(fā)送文件的請求,或者中斷了文件的傳輸!); this.textBox1.AppendText(您取消的發(fā)送文件的請求,或者中斷了文件的
46、傳輸!n); closefilefunction(); resumefilefunction(); if (Button)sender).Text = 拒絕) sendfunction(對方拒絕了您傳送文件的請求!); this.textBox1.AppendText(您拒絕了對方傳送文件的請求!n); resumefilefunction(); closefilefunction(); catch (Exception ex) MessageBox.Show(ex.Message, 錯誤提示); /連接或接受按鈕觸發(fā)的事件 public void button4_Click(object s
47、ender, EventArgs e) if (Button)sender).Text = 連接) try if (sendsocket = null) remoteendpoint = new IPEndPoint(IPAddress.Parse(textBox2.Text), 3000); sendsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sendsocket.Connect(remoteendpoint); requestmessage = IP地址為 + i
48、p0.ToString() + 的機器想與您通信,您接受嗎?; sendfunction(requestmessage); this.textBox1.AppendText(您發(fā)起了一個連接請求!n); if (th0 != null) if (th0.IsAlive = true) this.th0.Abort(); /連接的時候打開 openth1(); /發(fā)方,主動連接的那一方的監(jiān)聽線程 else this.textBox1.AppendText(您已經(jīng)發(fā)起了連接請求!正在等待對方應(yīng)答.n); catch (Exception ex) MessageBox.Show(ex.Message
49、); else if (Button)sender).Text = 接受) try if(receivesocket!=null) responsemessage= 對方接受了您的連接請求!; sendfunction(responsemessage); this.textBox1.AppendText(您同意了對方的連接請求!n); this.textBox2.Text =counteripstring; title = 已建立連接!; sendfunction(title); this.Text =title; this.button6.Text = 斷開連接; this.button4.
50、Enabled = false; this.button8.Enabled = false; this.button1.Enabled = true; this.button7.Enabled = true; this.textBox3.Enabled = true; this.button5.Enabled = true; if (th1 != null) if (th1.IsAlive = true) this.th1.Abort(); catch (Exception ex) MessageBox.Show(ex.Message); /發(fā)送聊天信息 private void button5_Click(object sender
溫馨提示
- 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)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年度廠房裝修工程合同管理及咨詢服務(wù)
- 2025年系列自動遙測氣象站項目建議書
- 秋季重點學(xué)科教學(xué)方案計劃
- 秘書職業(yè)女性的挑戰(zhàn)與機遇計劃
- 幼兒表達能力提升計劃
- 社區(qū)親和力提升的途徑計劃
- 資金流動性管理策略計劃
- 急診科應(yīng)急響應(yīng)機制強化計劃
- 藝術(shù)設(shè)計行業(yè)新年工作策略計劃
- 營造積極班級氣氛的實踐計劃
- 蘇州地圖高清矢量可填充編輯PPT模板(精美)
- 田字格(綠色標(biāo)準(zhǔn))
- 氧化鋁生產(chǎn)工藝教學(xué)(拜耳法)PPT課件
- 校本課程——生活中的化學(xué)
- 八字調(diào)候用神表
- 停車場巡視記錄表
- 河道景觀設(shè)計說明
- 《汽車性能評價與選購》課程設(shè)計
- 35kV絕緣導(dǎo)線門型直線桿
- 工程成本分析報告(新)
- 國際學(xué)術(shù)會議海報模板16-academic conference poster model
評論
0/150
提交評論