欢迎来到天天文库
浏览记录
ID:41032248
大小:21.91 KB
页数:8页
时间:2019-08-14
《c# socket 编程》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
/Socket基本编程//服务端:usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Text;usingSystem.Threading; Threadmythread;Socketsocket;//清理所有正在使用的资源。PRotectedoverridevoidDispose(booldisposing){try { socket.Close();//释放资源 mythread.Abort();//中止线程 } catch{} if(disposing){if(components!=null){components.Dispose();}}base.Dispose(disposing);}publicstatic ipAddressGetServerIP(){IPHostEntryieh=Dns.GetHostByName(Dns.GetHostName());returnieh.AddressList[0];}privatevoidBeginListen(){IPAddressServerIp=GetServerIP();IPEndPointiep=newIPEndPoint(ServerIp,8000); socket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); byte[]byteMessage=newbyte[100];this.label1.Text=iep.ToString();socket.Bind(iep);//dowhile(true){try{socket.Listen(5);SocketnewSocket=socket.Accept();newSocket.Receive(byteMessage); stringsTime=DateTime.Now.ToShortTimeString();stringmsg=sTime+":"+"Messagefrom:";msg+=newSocket.RemoteEndPoint.ToString()+Encoding.Default.GetString(byteMessage);this.listBox1.Items.Add(msg); }catch(SocketExceptionex){this.label1.Text+=ex.ToString();}}//while(byteMessage!=null);}//开始监听privatevoidbutton1_Click(objectsender,System.EventArgse){try{mythread=newThread(newThreadStart(BeginListen));mythread.Start(); } catch(System.Exceptioner){MessageBox.Show(er.Message,"完成",MessageBoxButtons.OK,MessageBoxIcon.Stop);}} //客户端: usingSystem.Net;usingSystem.Net.Sockets;usingSystem.Text; privatevoidbutton1_Click(objectsender,System.EventArgse){BeginSend();}privatevoidBeginSend(){stringip=this.txtip.Text;stringport=this.txtport.Text; IPAddressserverIp=IPAddress.Parse(ip);intserverPort=Convert.ToInt32(port);IPEndPointiep=newIPEndPoint(serverIp,serverPort);byte[]byteMessage;//do//{Socketsocket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);socket.Connect(iep); byteMessage=Encoding.ASCII.GetBytes(textBox1.Text);socket.Send(byteMessage);socket.Shutdown(SocketShutdown.Both);socket.Close();//}//while(byteMessage!=null); } 基于TCP协议的发送和接收端 TCP协议的接收端 usingSystem.Net.Sockets;//使用到TcpListen类usingSystem.Threading;//使用到线程usingSystem.IO;//使用到StreamReader类 intport=8000;//定义侦听端口号privateThreadthThreadRead;//创建线程,用以侦听端口号,接收信息privateTcpListenertlTcpListen;//侦听端口号privateboolblistener=true;//设定标示位,判断侦听状态privateNetworkStreamnsStream;//创建接收的基本数据流privateStreamReadersrRead;privateSystem.Windows.Forms.StatusBarstatusBar1;privateSystem.Windows.Forms.Buttonbutton1;privateSystem.Windows.Forms.ListBoxlistBox1;//从网络基础数据流中读取数据privateTcpClienttcClient; privatevoidListen(){try{tlTcpListen=newTcpListener(port);//以8000端口号来初始化TcpListener实例tlTcpListen.Start();//开始监听statusBar1.Text="正在监听";tcClient=tlTcpListen.AcceptTcpClient();//通过TCP连接请求nsStream=tcClient.GetStream();//获取用以发送、接收数据的网络基础数据流srRead=newStreamReader(nsStream);//以得到的网络基础数据流来初始化StreamReader实例statusBar1.Text="已经连接!"; while(blistener)//循环侦听{stringsMessage=srRead.ReadLine();//从网络基础数据流中读取一行数据if(sMessage=="STOP")//判断是否为断开TCP连接控制码 {tlTcpListen.Stop();//关闭侦听nsStream.Close();//释放资源srRead.Close();statusBar1.Text="连接已经关闭!";thThreadRead.Abort();//中止线程return;} stringsTime=DateTime.Now.ToShortTimeString();//获取接收数据时的时间listBox1.Items.Add(sTime+""+sMessage);}}catch(System.Security.SecurityException){MessageBox.Show("侦听失败!","错误");}}//开始监听privatevoidbutton1_Click(objectsender,System.EventArgse){thThreadRead=newThread(newThreadStart(Listen));thThreadRead.Start();//启动线程button1.Enabled=false;}//清理所有正在使用的资源。protectedoverridevoidDispose(booldisposing){try{tlTcpListen.Stop();//关闭侦听nsStream.Close();srRead.Close();//释放资源thThreadRead.Abort();//中止线程}catch{} if(disposing) {if(components!=null){components.Dispose();}}base.Dispose(disposing);} TCP协议的发送端 usingSystem.Net.Sockets;//使用到TcpListen类usingSystem.Threading;//使用到线程usingSystem.IO;//使用到StreamWriter类usingSystem.Net;//使用IPAddress类、IPHostEntry类等 privateStreamWriterswWriter;//用以向网络基础数据流传送数据 privateNetworkStreamnsStream;//创建发送数据的网络基础数据流 privateTcpClienttcpClient;privateSystem.Windows.Forms.Buttonbutton1;privateSystem.Windows.Forms.TextBoxtextBox1;privateSystem.Windows.Forms.Buttonbutton2;privateSystem.Windows.Forms.TextBoxtextBox2;privateSystem.Windows.Forms.StatusBarstatusBar1;privateSystem.Windows.Forms.Labellabel1;privateSystem.Windows.Forms.Labellabel2;//通过它实现向远程主机提出TCP连接申请 privatebooltcpConnect=false;//定义标识符,用以表示TCP连接是否建立 //连接 privatevoidbutton1_Click(objectsender,System.EventArgse){IPAddressipRemote;try{ipRemote=IPAddress.Parse(textBox1.Text);}catch//判断给定的IP地址的合法性{ MessageBox.Show("输入的IP地址不合法!","错误提示!");return;} IPHostEntryipHost;try{ipHost=Dns.Resolve(textBox1.Text); }catch//判断IP地址对应主机是否在线{MessageBox.Show("远程主机不在线!","错误提示!");return;} stringsHostName=ipHost.HostName;try{TcpClienttcpClient=newTcpClient(sHostName,8000);//对远程主机的8000端口提出TCP连接申请nsStream=tcpClient.GetStream();//通过申请,并获取传送数据的网络基础数据流 swWriter=newStreamWriter(nsStream);//使用获取的网络基础数据流来初始化StreamWriter实例button1.Enabled=false;button2.Enabled=true;tcpConnect=true;statusBar1.Text="已经连接!";}catch{MessageBox.Show("无法和远程主机8000端口建立连接!","错误提示!");return;}} //发送privatevoidbutton2_Click(objectsender,System.EventArgse){ if(textBox2.Text!=""){swWriter.WriteLine(textBox2.Text);//刷新当前数据流中的数据swWriter.Flush();}else{MessageBox.Show("发送信息不能为空!","错误提示!");}}//清理所有正在使用的资源。protectedoverridevoidDispose(booldisposing){if(tcpConnect){swWriter.WriteLine("STOP");//发送控制码 swWriter.Flush();//刷新当前数据流中的数据 nsStream.Close();//清除资源swWriter.Close();}if(disposing){if(components!=null){components.Dispose();}}base.Dispose(disposing);}
此文档下载收益归作者所有
举报原因
联系方式
详细说明
内容无法转码请点击此处