TCP UDP通讯编程Word文件下载.docx
《TCP UDP通讯编程Word文件下载.docx》由会员分享,可在线阅读,更多相关《TCP UDP通讯编程Word文件下载.docx(27页珍藏版)》请在冰豆网上搜索。
(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)
您输入的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)
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();
//开始监听
服务器Taking...."
richTextBox1.Clear();
服务器已启动"
btnImgFile.Enabled=true;
btn_start.Enabled=false;
btn_stop.Enabled=true;
catch(Exceptionex)
服务器:
+ex.Message);
this.btn_start.Enabled=true;
//接收客户端信息
publicvoidAcceptMessage()//异步接收信息后台线程方法
this.clientSocket=socket.Accept();
this.richTextBox1.Clear();
服务器连接成功"
while(true)
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>
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)
服务器"
+se.Message);
//点击“发送”按钮
privatevoidbtn_send_Click(objectsender,EventArgse)
if(txt1_sendinfo.Text=="
请?
先è
输?
入?
内ú
容╕!
?
txt1_sendinfo.Clear();
txt1_sendinfo.Focus();
if(imgflag==1)
//发送图片时
byte[]imgSize=newbyte[4];
//将32位整数值转换为字节数组
imgSize=System.BitConverter.GetBytes(img.Length+1);
//其中加1是因为后面了一个101做分隔符
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();
\n"
fstream.Flush();
fstream.Close();
//此流必须在这里才可以消除
txt1_sendinfo.Paste();
this.richTextBox1.Focus();
this.txt1_sendinfo.Text="
this.txt1_sendinfo.Focus();
imgflag=0;
//复原
//不执行后面的传输文本信息
catch(System.Exceptionex)
//发送文本信息时
stringstr="
+txt1_sendinfo.Text;
inti=str.Length;
if(i==0)
//因为astr为aUnicode编括码,每字符占2个字节,所以实害际字节数应为字符个数*2
i*=2;
dataSize=System.BitConverter.GetBytes(i+1);
//其中加1因为后面写了一个做分隔符
byte[]sendbytes=System.Text.Encoding.Unicode.GetBytes(str);
netStream.Write(dataSize,0,4);
netStream.WriteByte
(1);
netStream.Write(sendbytes,0,sendbytes.Length);
richTextBox1.SelectionColor=Color.SteelBlue;
this.richTextBox1.AppendText(str+"
this.txt1_sendinfo.Rtf="
//断开连接
privatevoidbtn_stop_Click(objectsender,EventArgse)
socket.Close();
thread.Abort();
thread.Join(10);
btn_stop.Enabled=false;
+DateTime.Now.ToString()+"
服务器断开连接"
.....\r\n"
//接收文本
privatevoidUpdateMessage(stringstrmsg)//将异步接收到的信息显示在富文本框里
this.richTextBox1.SelectionColor=Color.LightCoral;
this.richTextBox1.AppendText(strmsg+"
//接收图片信息
privatevoidViewImg(Streams)//将异步接收到的信息显示在富文本框里
richTextBox1.SelectionStart=richTextBox1.Text.Length;
richTextBox1.SelectionColor=Color.LightCoral;
服务器接图片"
Clipboard.SetDataObject(Image.FromStream(s));
//利用剪切板
richTextBox1.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);
imgflag=1;
//退出聊天室
privatevoidbtn_Exit_Click(objectsender,EventArgse)
if(btn_stop.Enabled!
=true)
this.Close();
Application.Exit();
请先断开连接?
//取消发送
privatevoidbtnRest_Click(objectsender,EventArgse)
//清屏
privatevoidbtnClear_Click(objectsender,EventArgse)
}
2.客户端
tab1.Visi