C#-局域网内的TCP传输_第1页
C#-局域网内的TCP传输_第2页
C#-局域网内的TCP传输_第3页
C#-局域网内的TCP传输_第4页
C#-局域网内的TCP传输_第5页
已阅读5页,还剩27页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、精选优质文档-倾情为你奉上精选优质文档-倾情为你奉上专心-专注-专业专心-专注-专业精选优质文档-倾情为你奉上专心-专注-专业局域网内的tcp传输刚学了C#的tcp传输,借鉴了以前前辈的一些做法,写了一个简单的局域网内的聊天传文件的小软件,界面如下:本程序需要同时在两个能够正常通信的处于同一局域网的电脑上同时开启才能正常使用。不分主机和客户端。(不过需要将相应的端口号做些改动,即将以下代码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);)如果在一台电脑上测试:只需将程序复制两份,同时打开。将复制的部分代码做以下改变(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))以下是本程序的执行界面:以下分别是本程序在两台机器上建立连接后,能正常通信的一些界面(是在自己的电脑上测试的,所以两端的IP是一样的):本程序只能在局域网内进行通信,若要与外网通信,需要将代码进行扩充,有兴趣的朋友可以尝试一下。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); /用来传送文本的本地网络端点 localendpoint = new IPEndPoint(ip0,2000); /用来传送文件的本地网络端点 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(请选择监听或者主动连接!rn请确保对方处于监听状态才可发出连接申请!rn否则需重启这个程序!n); catch (Exception ex) MessageBox.Show(ex.Message); /监听的时候打开 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(); / / 将对方发过来的信息显示到文本框 / / private void showmessagetotextbox1(string str) if (str = 已建立连接!) this.Text = str; if(str.Length9) if (str.

12、Substring(0,9)= 对方断开了当前连接) 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; /听方,等待被连接的那一方的监听程序 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) = 对方断开了当前连接) this.Invoke(new resume(resumefunction); closefunction(); if (receivestring.Length 12) if (receivestring.Substring(0,12)= 对方取消了发送文件的请求) this.Invoke(new resume(resumefilefunction); closefilefunction(); if (receivestring = 对方拒绝了您传送文件的请求!) this.Invoke(new resume

18、(resumefilefunction); closefilefunction(); catch(Exception ex) MessageBox.Show(ex.Message); /发方,主动连接的那一方的监听程序 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) = 对方断开了当前连接) this.Invoke(new resume(resumefunction); closefunction(); if (receivestring.Leng

20、th 12) if (receivestring.Substring(0,12)= 对方取消了发送文件的请求) 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); /传文件时,主动发送文件的一方的传文件程序 private void transferfile() try /这里每次发之前都要受到一个对方发过来的信号是为了保证收发同步 if (filereceivesocket != null) if (filereceivesocket.Connected) /先发送文件名称,以便在保存时有文件的原始名字 filebytestosend = new bytefilename.Length; filebytestosend = Encoding.Unicode.GetBytes(filename); filere

22、ceivesocket.Send(filebytestosend, filebytestosend.Length, 0); /随后发送文件的长度,以便后面确定切发送的次数 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); /最后发送文件本身的内容 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都要清零,否则会留下上次传输数据的长度的痕迹 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 = 下面是长度; /这是随意发送的一个信号,主要是为了收发同步,以免这边还没有接收完那边全发送了 sendfilefunction(filestringtosend); length = filesendsocket.Receive(filebytesreceived, filebytesreceived.Length, 0); filerecei

28、vestring = Encoding.Unicode.GetString(filebytesreceived,0,length); /获取传送的文件的长度 receivedfilelength = long.Parse(filereceivestring); /将数字的字符串表示形式转换为它的等效 64 位有符号整数。 filestringtosend = 开始; /这也是随意发送的一个记号,为收发同步 sendfilefunction(filestringtosend); FileStream fs = new FileStream(savedfilepath, FileMode.Crea

29、te, FileAccess.Write); /这里显示进度条 this.Invoke(new resume(receivedprogressbar); temp2 = 0; /这里每次temp2都要清零,否则会留下上次收到数据的长度的痕迹 this.Invoke(new MethodInvoker(this.timer2.Start); /下面是接收文件的具体内容 while (temp2 0 & temp2receivedfilelength) this.timer2.Stop(); MessageBox.Show(文件在传输过程中遇到错误!); /显示发方的进度条和标签 private

30、void sendprogressbar() progressBar1.Visible = true; progressBar1.Maximum = (int)sendfilelength; this.label2.Visible = true; /及时的更改发方当前的进度条的值 private void sendprogressbar1() gressBar1.Value = (int)temp; /显示收方的进度条和标签 private void receivedprogressbar() progressBar1.Visible = true; progressBar1.Maximum

31、= (int)receivedfilelength; this.label2.Visible = true; /及时的更改收方当前的进度条的值 private void receivedprogressbar1() gressBar1.Value = (int)temp2; /向对方发送文本消息 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); /接收文件方向发方发送消息,以便同步 private void sendfilefunction(string str) filebytestosend = new bytestr.Lengt

33、h; filebytestosend = Encoding.Unicode.GetBytes(str); filesendsocket.Send(filebytestosend, filebytestosend.Length, 0); / /这要运行到beginacceptsocket函数时,就会开辟这个线程 /一直等到有对方发出连接请求来,否则这个线程一直在后台运行 /所以有时监听然后复位后,这个监听线程还是在运行, /以至于复位后选择主动连接,这个线程仍然在运行, /以至于后续操作中有tcplistener.stop()会引发这里的异常 / / private void startrece

34、ivesocket(IAsyncResult ar) try receivesocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); /如果后面再加一个begin,这个一直在后台等待被连接?(得再想想) receivesocket = tcplistener.EndAcceptSocket(ar); openth0(); /听方,等待被连接的那一方的监听线程 /tcplistener.BeginAcceptSocket(callback, null); /这里的最后一句注释与不注释

35、,有没有区别? catch (Exception) finally System.Threading.Thread.CurrentThread.Abort(); /这是等待对方接受传送文件申请时一直在后台等待应答的线程 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(); /关闭用于发送、接收信息的套接字和线程 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; /关闭用于发送、接收文件的套接字和线程 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、断开连接等操作后恢复到程序刚开始打开时的状态 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 = 监听; this.Text = 文件传输; this.button1.E

40、nabled = false; this.button7.Enabled = false; this.textBox3.Enabled = false; this.textBox3.Clear(); this.button5.Enabled = false; /断开文件传输等操作后恢复到一般发送信息的状态 private void resumefilefunction() this.button1.Enabled = true; this.button2.Text = 发送; this.button2.Enabled=false; this.button3.Text = 接收; this.bu

41、tton3.Enabled=false; this.label2.Visible = false; gressBar1.Visible = false; /选择文件按钮触发的事件 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(文件未发送,请按发送键发送您选择的文件!); filename = System.IO.Path.GetFileName(filepath); this.button2.Enabled = true; else MessageBox.Show(未选中文件,请重新选择!); /发送或接受按钮触发的事件 private void button2_Click(object sender, EventArgs e) try if (Button)sender).Text = 发送) sendfunction(对方向您传送文件 + filename + ,您接受吗?); filetcpliste

43、ner.Start(); filetcplistener.BeginAcceptSocket(filecallback, null); this.textBox1.AppendText(您发送了文件!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); /接收按钮触发的事件 private void button3_Click(object sender, EventArgs e) try if (Button)sender).Text = 取消) filetcplistener.Stop(); sendfunction(对方取消了发送文件的请求,或者中断了文件的传输!); this.textBox1.AppendText(您取消的发送文件的请求,或者中断了文件的

46、传输!n); closefilefunction(); resumefilefunction(); if (Button)sender).Text = 拒绝) sendfunction(对方拒绝了您传送文件的请求!); this.textBox1.AppendText(您拒绝了对方传送文件的请求!n); resumefilefunction(); closefilefunction(); catch (Exception ex) MessageBox.Show(ex.Message, 错误提示); /连接或接受按钮触发的事件 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(您发起了一个连接请求!n); if (th0 != null) if (th0.IsAlive = true) this.th0.Abort(); /连接的时候打开 openth1(); /发方,主动连接的那一方的监听线程 else this.textBox1.AppendText(您已经发起了连接请求!正在等待对方应答.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); /发送聊天信息 private void button5_Click(object sender

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论