欢迎来到天天文库
浏览记录
ID:38267343
大小:222.12 KB
页数:9页
时间:2019-06-07
《TCP实验关于C#的CS编程》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、组C/S模式的编程实例——C#语言编写报告人:实验分组:班级:学号:负责内容:TCPserver1.实验目的利用C#编程,通过TCP的数据连接和传输的方式,编写一个基于TCP的CS模式的简易聊天程序。2.实验思想和方案TCPIP协议栈。TCPIP参考模型分为四个层次:应用层,传输层,网络互连层和主机到网络层。在TCP中常用的类有:TcpListener类,TcpClient类,NetworkStream等。通讯流程图:部分源代码:usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentMode
2、l;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Threading;namespaceTCPClient{publicpartialclassForm1:Form{publicSocketnewclient;publicboolConnected;publicThreadmyThread;publicdelegatevoi
3、dMyInvoke(stringstr);publicForm1(){InitializeComponent();}publicvoidConnect(){byte[]data=newbyte[1024];newclient=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);stringipadd=serverIP.Text.Trim();intport=Convert.ToInt32(serverPort.Text.Trim());IPEndPointie=newIPEndP
4、oint(IPAddress.Parse(ipadd),port);try{newclient.Connect(ie);connect.Enabled=false;Connected=true;}catch(SocketExceptione){MessageBox.Show("连¢?接¨®服¤t务?器¡Â失º¡ì败㨹"+e.Message);return;}ThreadStartmyThreaddelegate=newThreadStart(ReceiveMsg);myThread=newThread(myThreaddelegate);myThread.Start(
5、);}publicvoidReceiveMsg(){while(true){byte[]data=newbyte[1024];intrecv=newclient.Receive(data);stringstringdata=Encoding.UTF8.GetString(data,0,recv);showMsg(stringdata+"r");//receiveMsg.AppendText(stringdata+"r");}}publicvoidshowMsg(stringmsg){{//在¨²线?程¨¬里¤?以°?安ã2全¨?方¤?式º?调Ì¡Â用®?控?件
6、tif(receiveMsg.InvokeRequired){MyInvoke_myinvoke=newMyInvoke(showMsg);receiveMsg.Invoke(_myinvoke,newobject[]{msg});}else{receiveMsg.AppendText(msg);}}}privatevoidSendMsg_Click(objectsender,EventArgse){intm_length=mymessage.Text.Length;byte[]data=newbyte[m_length];data=Encoding.UTF8.GetBy
7、tes(mymessage.Text);inti=newclient.Send(data);showMsg("我¨°说¦Ì:êo"+mymessage.Text+"r");//receiveMsg.AppendText("我¨°说¦Ì:êo"+mymessage.Text+"r");mymessage.Text="";//newclient.Shutdown(SocketShutdown.Both);}privatevoidconnect_Click(objectsender,EventArgse){Connect
此文档下载收益归作者所有