




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、局域网内的tcp传输刚学了C#的tcp传输,借鉴了以前前辈的一些做法,写了一个简单的局域网内的聊天传文件的小软件,界面如下:本程序需要同时在两个能够正常通信的处于同一局域网的电脑上同时开启才能正常使用。不分主机和客户端。(不过需要将相应的端口号做些改动,即将以下代码remoteendpoint =newIPEndPoint(IPAddress.Parse(textBox2.Text),3000)改为remoteendpoint = new IPEndPoint(IPAddress.Parse(textBox2.Text),2000),fileremoteendpoint= new IPEndP
2、oint(IPAddress.Parse(textBox2.Text),5000)改为fileremoteendpoint= new IPEndPoint(IPAddress.Parse(textBox2.Text),4000);)如果在一台电脑上测试:只需将程序复制两份,同时打开。将复制的部分代码做以下改变(localendpoint = new IPEndPoint(ip0,2000)改为localendpoint = new IPEndPoint(ip0,3000),filelocalendpoint = new IPEndPoint(ip0, 4000)改为filelocalendpo
3、int = 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),5000)改为fileremoteendpoint= new IPEndPoint(IPAddress.Parse(textBox
4、2.Text),4000))以下是本程序的执行界面:以下分别是本程序在两台机器上建立连接后,能正常通信的一些界面(是在自己的电脑上测试的,所以两端的IP是一样的):本程序只能在局域网内进行通信,若要与外网通信,需要将代码进行扩充,有兴趣的朋友可以尝试一下。using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Fo
5、rms;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; Socket receivesocket; Socket filereceivesocket; Socket filesen
6、dsocket; AsyncCallback callback; AsyncCallback filecallback; IPEndPoint localendpoint; IPEndPoint remoteendpoint; IPEndPoint filelocalendpoint; IPEndPoint fileremoteendpoint; Thread th=new Thread4; string requestmessage; string receivestring; string responsemessage; string filereceivestring; string
7、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 bytestosend; byte bytesreceived= new byte8192; byte filebytesto
8、send; 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(); ip = Dns.GetHostAddresses(str); /用来传送文本的本地网络端点 localendpoin
9、t = new IPEndPoint(ip0,2000); /用来传送文件的本地网络端点 filelocalendpoint = new IPEndPoint(ip0, 4000); callback = new AsyncCallback(startreceivesocket); filecallback = new AsyncCallback(startfilereceivesocket); tcplistener = new TcpListener(localendpoint); filetcplistener = new TcpListener(filelocalendpoint);
10、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.IsAlive = false) th0.Start(); /连接的时候打开 private void openth1() th
11、1 = 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.Substring(0,9)= 对方断开了当前连接) this.Text = 连接断开!; if (str = 对方接受了您的
12、连接请求!) 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 = true; if (str.Substring(0, 2) = IP) iptemp = str.Substring(5, st
13、r.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.Substring(0, 8) = 对方向您传送文件) this.button1.Enabled = false; this.bu
14、tton2.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.AppendText(rnrn); /接受对方传过来的文件时弹出的对话框 private void showdialog() if (saveF
15、ileDialog1.ShowDialog() = DialogResult.OK) savedfilepath = saveFileDialog1.FileName; /听方,等待被连接的那一方的监听程序 private void th0process() while(true) try if (receivesocket != null) receivesocket.Blocking = true; length = receivesocket.Receive(bytesreceived, bytesreceived.Length, 0); receivestring = System.T
16、ext.Encoding.GetEncoding(GB2312).GetString(bytesreceived, 0, length); this.Invoke(new showmessage(showmessagetotextbox1), new object receivestring ); /这里直接用赋值语句不行,因为这里是另外开的线程 /不是主线程,所以不能直接对form上的控件直接进行访问 if (receivestring.Length 9) if (receivestring.Substring(0, 9) = 对方断开了当前连接) this.Invoke(new resum
17、e(resumefunction); closefunction(); if (receivestring.Length 12) if (receivestring.Substring(0,12)= 对方取消了发送文件的请求) this.Invoke(new resume(resumefilefunction); closefilefunction(); if (receivestring = 对方拒绝了您传送文件的请求!) this.Invoke(new resume(resumefilefunction); closefilefunction(); catch(Exception ex)
18、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.Encoding.GetEncoding(GB2312).GetString(bytesreceived, 0, length
19、); 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.Length 12) if (receivestring.Substring(0,12)= 对方取消了发送文件的请求) this.In
20、voke(new resume(resumefilefunction); closefilefunction(); if (receivestring = 对方拒绝了您的连接请求!) closefunction(); if (receivestring = 对方拒绝了您传送文件的请求!) this.Invoke(new resume(resumefilefunction); closefilefunction(); catch(Exception ex) MessageBox.Show(ex.Message); /传文件时,主动发送文件的一方的传文件程序 private void transf
21、erfile() try /这里每次发之前都要受到一个对方发过来的信号是为了保证收发同步 if (filereceivesocket != null) if (filereceivesocket.Connected) /先发送文件名称,以便在保存时有文件的原始名字 filebytestosend = new bytefilename.Length; filebytestosend = Encoding.Unicode.GetBytes(filename); filereceivesocket.Send(filebytestosend, filebytestosend.Length, 0); /
22、随后发送文件的长度,以便后面确定切发送的次数 filereceivesocket.Blocking = true; length = filereceivesocket.Receive(filebytesreceived, filebytesreceived.Length, 0); startstring = Encoding.Unicode.GetString(filebytesreceived, 0, length); if (startstring = 下面是长度) FileInfo filetosend = new FileInfo(filepath); sendfilelength
23、= filetosend.Length; filebytestosend = new bytesendfilelength.ToString().Length; filebytestosend = Encoding.Unicode.GetBytes(sendfilelength.ToString(); filereceivesocket.Send(filebytestosend, filebytestosend.Length, 0); /最后发送文件本身的内容 filereceivesocket.Blocking = true; length = filereceivesocket.Recei
24、ve(filebytesreceived, filebytesreceived.Length, 0); startstring = Encoding.Unicode.GetString(filebytesreceived, 0, length); if (startstring = 开始) FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read); filebytestosend = new byte32768; /这里显示进度条 this.Invoke(new resume(sendprogressbar
25、); /timer是主窗体上的控件,线程间不能操作 temp = 0; /这里每次temp都要清零,否则会留下上次传输数据的长度的痕迹 this.Invoke(new MethodInvoker(this.timer1.Start); while (temp 0 & temp sendfilelength) this.timer1.Stop(); MessageBox.Show(文件在传输过程中遇到错误!); /传文件时,接收文件的一方的接受文件程序 private void receivefile() try if (filesendsocket != null) if (filesends
26、ocket.Connected) filesendsocket.Blocking = true; length = filesendsocket.Receive(filebytesreceived, filebytesreceived.Length, 0); filereceivestring=Encoding.Unicode.GetString(filebytesreceived,0,length); /接收从对方穿过来的文件的原有的文件名 saveFileDialog1.Title = 另存为; saveFileDialog1.FileName = filereceivestring; /
27、显示“另存为”对话框 this.Invoke(new show(showdialog); filestringtosend = 下面是长度; /这是随意发送的一个信号,主要是为了收发同步,以免这边还没有接收完那边全发送了 sendfilefunction(filestringtosend); length = filesendsocket.Receive(filebytesreceived, filebytesreceived.Length, 0); filereceivestring = Encoding.Unicode.GetString(filebytesreceived,0,lengt
28、h); /获取传送的文件的长度 receivedfilelength = long.Parse(filereceivestring); /将数字的字符串表示形式转换为它的等效 64 位有符号整数。 filestringtosend = 开始; /这也是随意发送的一个记号,为收发同步 sendfilefunction(filestringtosend); FileStream fs = new FileStream(savedfilepath, FileMode.Create, FileAccess.Write); /这里显示进度条 this.Invoke(new resume(received
29、progressbar); temp2 = 0; /这里每次temp2都要清零,否则会留下上次收到数据的长度的痕迹 this.Invoke(new MethodInvoker(this.timer2.Start); /下面是接收文件的具体内容 while (temp2 0 & temp2receivedfilelength) this.timer2.Stop(); MessageBox.Show(文件在传输过程中遇到错误!); /显示发方的进度条和标签 private void sendprogressbar() progressBar1.Visible = true; progressBar
30、1.Maximum = (int)sendfilelength; this.label2.Visible = true; /及时的更改发方当前的进度条的值 private void sendprogressbar1() gressBar1.Value = (int)temp; /显示收方的进度条和标签 private void receivedprogressbar() progressBar1.Visible = true; progressBar1.Maximum = (int)receivedfilelength; this.label2.Visible = true;
31、/及时的更改收方当前的进度条的值 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 (receivesocket != null) if(receivesocket.Connected) receivesocket.Send(bytestosend, bytestosend.Length, 0); if (sendsocket != null) if(sends
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025盐城幼儿师范高等专科学校辅导员考试试题及答案
- 2025年广东省深圳市十五校中考历史二模试卷
- 新生儿正常生理特征及护理要点
- 换牙期卫生与保健
- 2025年游戏设计专业考试题及答案
- 环境科学与生态理论2025年考试试卷及答案
- 网络工程师考试题及答案2025年
- 2025年物流与供应链管理职业能力考核试题及答案
- 2025年网络教育与在线学习考试试卷及答案
- 2025年图书馆学基础知识考试试题及答案
- 【词汇】近五年高考英语超纲词+音标+词义
- 人教版五年级数学下册期末试卷(一套)
- 山东省东营市2024年中考英语真题(含答案)
- 2024河南许昌胖东来考察报告
- 物流无人机垂直起降场选址与建设规范
- JGJ64-2017饮食建筑设计标准(首发)
- 《成人四肢血压测量的中国专家共识(2021)》解读
- 旅游行业旅行社经理劳动合同样本
- DBJ50-T-417-2022 建筑施工高处坠落防治安全技术标准
- 医院物业挂靠协议书
- 部编版五年级下册道德与法治期末测试卷带答案(考试直接用)
评论
0/150
提交评论