TCP UDP通讯编程.docx
- 文档编号:4307422
- 上传时间:2022-11-29
- 格式:DOCX
- 页数:27
- 大小:1.53MB
TCP UDP通讯编程.docx
《TCP UDP通讯编程.docx》由会员分享,可在线阅读,更多相关《TCP UDP通讯编程.docx(27页珍藏版)》请在冰豆网上搜索。
TCPUDP通讯编程
TCP/UDP程序开发
使用C#制作简易qq
TCP、UDP程序开发
1.实验课时
8学时
2.实验目的
开发TCP/UDP协议应用程序,掌握网络应用程序的工作原理。
通过本实验,深入理解TCP和UDP协议的异同点,了解网络协议的工作过程,学会网络通信编程的基本方法,能够编制网络应用程序。
3.实验内容
(1)了解和掌握“基于UDP——面向无连接的应用程序”和“基于TCP——面向连接的应用程序”的运行机制和编程方法。
(2)选择以下一个内容,编写一个网络通信应用程序
1聊天程序;
2邮件收发程序;
3HTTP服务器程序。
4.实验要求
(1)使用任意编程语言(如Java,C,VB,Delphi等)编写基于TCP或UDP协议的网络应用程序。
(2)总结实验过程,内容包括:
方案、程序、调试、结果、分析、结论。
5.实验设备
(1)硬件要求:
计算机、Internet网。
(2)软件要求:
Windows操作系统、相关软件开发工具(如MicrosoftVisualStudio,JDK等)。
6.预习要求
(1)复习TCP/UDP协议原理。
(2)复习应用进程跨越网络通信的基本编程方法。
(3)复习聊天、邮件、HTTP服务的相关原理。
(4)熟悉相关编程语言及编程工具环境。
7.注意事项
(1)遵守实验纪律,爱护实验设备。
(2)提交详细实验报告一份。
实验过程和结果不能简单地复制相关命令或内容,要有理解和分析。
8.程序代码
1.服务器端
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Threading;
usingSystem.IO;
namespaceWindowsFormsApplication1
{
publicpartialclassForm1:
Form
{
publicForm1()
{
InitializeComponent();
this.Init();
tab2.Visible=true;
tab3.Visible=false;
tab1.Visible=false;
}
privatevoidbtnLog_Click(objectsender,EventArgse)
{
if(txtIP.Text==""||txtPort.Text=="")
{
MessageBox.Show("请输入IP地址或端口号","提示信息",MessageBoxButtons.OK,MessageBoxIcon.Warning,MessageBoxDefaultButton.Button1);
return;
}
else
{
try
{
IPAddressipadd=IPAddress.Parse(this.txtIP.Text);
intport=Convert.ToInt32(this.txtPort.Text);
tab3.Visible=true;
tab1.Visible=true;
this.Init2();
this.btnImgFile.Enabled=false;
this.Text="服务器"+DateTime.Now.ToString()+""+DateTime.Now.DayOfWeek.ToString();
richTextBox1.AppendText("System:
服务器已进入聊天室"+DateTime.Now.ToLongTimeString()+"->.....\r\n");
stringSerIp=txtIP.Text.ToString();
stringSerPort=txtPort.Text.ToString();
labip.Text="IP地址:
"+""+SerIp+"";
labport.Text="端口号:
"+""+SerPort;
}
catch(Exception)
{
MessageBox.Show("您输入的IP地址或端口号不正确\n请重新输入!
","错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
}
//重置服务器信息
privatevoidbtnResent_Click_1(objectsender,EventArgse)
{
txtIP.Clear();
txtPort.Clear();
}
privatevoidInit()
{
richTextBox1.Visible=false;
txt1_sendinfo.Visible=false;
}
privatevoidInit2()
{
richTextBox1.Visible=true;
txt1_sendinfo.Visible=true;
}
privateOpenFileDialogopenfiledialog=newOpenFileDialog();
privateSaveFileDialogsavefiledialog=newSaveFileDialog();
privatebyte[]img;//传输图片用字节数组
privateintimgflag=0;
privateFileStreamfstream;
publicdelegatevoidUpdateRichTextBox(stringmsg);//异步委托代理
publicdelegatevoidUpdateImg(Streams);
privateSocketsocket;//服务器端套接字
privateSocketclientSocket;//客户端连接套接字
privateThreadthread;
//启动服务器开始监
privatevoidbtn_start_Click(objectsender,EventArgse)
{
try
{
IPAddressip=IPAddress.Parse(this.txtIP.Text);
IPEndPointserver=newIPEndPoint(ip,Int32.Parse(this.txtPort.Text));
//创建服务器套接字
socket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
socket.Bind(server);//绑定端口号
socket.Listen(10);
thread=newThread(newThreadStart(AcceptMessage));
thread.Start();//开始监听
this.Text="服务器Taking....";
richTextBox1.Clear();
richTextBox1.AppendText("System:
服务器已启动"+DateTime.Now.ToLongTimeString()+"->.....\r\n");
btnImgFile.Enabled=true;
btn_start.Enabled=false;
btn_stop.Enabled=true;
}
catch(Exceptionex)
{
MessageBox.Show("服务器:
"+ex.Message);
this.btn_start.Enabled=true;
}
}
//接收客户端信息
publicvoidAcceptMessage()//异步接收信息后台线程方法
{
this.clientSocket=socket.Accept();
this.richTextBox1.Clear();
richTextBox1.AppendText("System:
服务器连接成功"+DateTime.Now.ToLongTimeString()+"->.....\r\n");
while(true)
{
try
{
if(this.clientSocket==null||this.clientSocket.Connected==false)
break;
NetworkStreamnetStream=newNetworkStream(this.clientSocket);//通过yclientSocket对象获取NetworkStream对象//得到一条消息的长度
byte[]dataSize=newbyte[4];
netStream.Read(dataSize,0,4);
intsize=System.BitConverter.ToInt32(dataSize,0);
//循环接收直到一条完整的消息全部读入到字节数组中
byte[]message=newbyte[size];
intdataleft=size;
intstart=0;
if(size>0)
{
while(dataleft>0)
{
intrecv=netStream.Read(message,start,dataleft);
start+=recv;
dataleft-=recv;
}
if(message[0]==101)//101代表括传输图片
{
MemoryStreamms=newMemoryStream(message,1,message.Length-1);
richTextBox1.BeginInvoke(newUpdateImg(ViewImg),newobject[]{ms});
}
else//默认进行普通传输
{
stringMsg=System.Text.Encoding.Unicode.GetString(message,1,message.Length-1);
this.richTextBox1.BeginInvoke(newUpdateRichTextBox(UpdateMessage),newobject[]{Msg});
}
}
Thread.Sleep(100);
}
catch(System.Net.Sockets.SocketExceptionse)
{
MessageBox.Show("服务器"+se.Message);
}
}
}
//点击“发送”按钮
privatevoidbtn_send_Click(objectsender,EventArgse)
{
if(txt1_sendinfo.Text=="")
{
MessageBox.Show("请?
先è输?
入?
内ú容╕!
?
");
txt1_sendinfo.Clear();
txt1_sendinfo.Focus();
return;
}
if(imgflag==1)
{
//发送图片时
byte[]imgSize=newbyte[4];
//将32位整数值转换为字节数组
imgSize=System.BitConverter.GetBytes(img.Length+1);//其中加1是因为后面了一个101做分隔符
try
{
NetworkStreamnetStream=newNetworkStream(clientSocket);
netStream.Write(imgSize,0,4);
netStream.WriteByte(101);//分隔符
netStream.Write(img,0,img.Length);
netStream.Flush();
this.richTextBox1.SelectionColor=Color.SteelBlue;
this.richTextBox1.AppendText("服务器"+DateTime.Now.ToLongTimeString()+"\r\n");
this.richTextBox1.SelectionStart=this.richTextBox1.Text.Length;
Clipboard.SetDataObject(Image.FromStream(fstream));
richTextBox1.Paste();
this.richTextBox1.SelectionColor=Color.SteelBlue;
this.richTextBox1.AppendText("\n");
fstream.Flush();
fstream.Close();//此流必须在这里才可以消除
txt1_sendinfo.Paste();
this.richTextBox1.SelectionStart=this.richTextBox1.Text.Length;
this.richTextBox1.Focus();
this.txt1_sendinfo.Text="";
this.txt1_sendinfo.Focus();
imgflag=0;//复原
return;//不执行后面的传输文本信息
}
catch(System.Exceptionex)
{
MessageBox.Show("服务器"+ex.Message);
}
}
//发送文本信息时
this.richTextBox1.SelectionColor=Color.SteelBlue;
stringstr="服务器"+DateTime.Now.ToLongTimeString()+"\r\n"+txt1_sendinfo.Text;
inti=str.Length;
if(i==0)
{
return;
}
else
{
//因为astr为aUnicode编括码,每字符占2个字节,所以实害际字节数应为字符个数*2
i*=2;
}
byte[]dataSize=newbyte[4];
//将32位整数值转换为字节数组
dataSize=System.BitConverter.GetBytes(i+1);//其中加1因为后面写了一个做分隔符
byte[]sendbytes=System.Text.Encoding.Unicode.GetBytes(str);
try
{
NetworkStreamnetStream=newNetworkStream(clientSocket);
netStream.Write(dataSize,0,4);
netStream.WriteByte
(1);//分隔符
netStream.Write(sendbytes,0,sendbytes.Length);
netStream.Flush();
richTextBox1.SelectionColor=Color.SteelBlue;
this.richTextBox1.AppendText(str+"\n");
this.richTextBox1.SelectionStart=this.richTextBox1.Text.Length;
this.richTextBox1.Focus();
this.txt1_sendinfo.Rtf="";
this.txt1_sendinfo.Focus();
}
catch(System.Exceptionex)
{
MessageBox.Show("服务器"+ex.Message);
}
}
//断开连接
privatevoidbtn_stop_Click(objectsender,EventArgse)
{
socket.Close();
thread.Abort();
thread.Join(10);
this.btn_start.Enabled=true;
btn_stop.Enabled=false;
this.btnImgFile.Enabled=false;
this.Text="服务器"+DateTime.Now.ToString()+""+DateTime.Now.DayOfWeek.ToString();
this.richTextBox1.AppendText("System:
服务器断开连接"+DateTime.Now.ToLongTimeString()+"->.....\r\n");
}
//接收文本
privatevoidUpdateMessage(stringstrmsg)//将异步接收到的信息显示在富文本框里
{
this.richTextBox1.SelectionColor=Color.LightCoral;
this.richTextBox1.AppendText(strmsg+"\n");
this.richTextBox1.SelectionStart=this.richTextBox1.Text.Length;
this.richTextBox1.Focus();
this.txt1_sendinfo.Focus();
}
//接收图片信息
privatevoidViewImg(Streams)//将异步接收到的信息显示在富文本框里
{
richTextBox1.SelectionStart=richTextBox1.Text.Length;
richTextBox1.SelectionColor=Color.LightCoral;
richTextBox1.AppendText("服务器接图片"+DateTime.Now.ToLongTimeString()+"\r\n");
Clipboard.SetDataObject(Image.FromStream(s));//利用剪切板
richTextBox1.Paste();
richTextBox1.SelectionColor=Color.LightCoral;
richTextBox1.AppendText("\n");
richTextBox1.SelectionStart=richTextBox1.Text.Length;
richTextBox1.Focus();
txt1_sendinfo.Focus();
}
//上传图片文件中的图片
privatevoidbtnImgFile_Click(objectsender,EventArgse)
{
openfiledialog.Filter="所有文件t(*.*)位图文(*.bmp)文件t(.jpg)文件t(.gif)";
if(openfiledialog.ShowDialog()==DialogResult.OK)
{
Stringstrpath=openfiledialog.FileName;
fstream=newFileStream(strpath,FileMode.Open);
BinaryReaderbreader=newBinaryReader(fstream);
img=breader.ReadBytes((int)fstream.Length);
Clipboard.SetDataObject(Image.FromStream(fstream));
txt1_sendinfo.Paste();
imgflag=1;
}
}
//退出聊天室
privatevoidbtn_Exit_Click(objectsender,EventArgse)
{
if(btn_stop.Enabled!
=true)
{
this.Close();
Application.Exit();
}
else
{
MessageBox.Show("请先断开连接?
");
return;
}
}
//取消发送
privatevoidbtnRest_Click(objectsender,EventArgse)
{
txt1_sendinfo.Clear();
}
//清屏
privatevoidbtnClear_Click(objectsender,EventArgse)
{
this.richTextBox1.Clear();
}
}
}
2.客户端
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Threading;
usingSystem.IO;
namespaceWindowsFormsApplication1
{
publicpartialclassForm1:
Form
{
publicForm1()
{
InitializeComponent();
this.Init();
tab2.Visible=true;
tab3.Visible=false;
tab1.Visi
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- TCP UDP通讯编程 UDP 通讯 编程
![提示](https://static.bdocx.com/images/bang_tan.gif)