




已阅读5页,还剩9页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Socket基本编程最近由于要做一些Socket方面的项目,所以又温习了一下Socket和TCP协议编程的一些基本知识,整理一下放在这里。Socket基本编程服务端:using System.Net;using System.Net.Sockets;using System.Text;using System.Threading; Thread mythread ; Socket socket;/ 清理所有正在使用的资源。 protected override void Dispose( bool disposing ) try socket.Close();/释放资源 mythread.Abort ( ) ;/中止线程 catch if( disposing ) if (components != null) components.Dispose(); base.Dispose( disposing ); public static IPAddress GetServerIP() IPHostEntry ieh=Dns.GetHostByName(Dns.GetHostName(); return ieh.AddressList0; private void BeginListen() IPAddress ServerIp=GetServerIP(); IPEndPoint iep=new IPEndPoint(ServerIp,8000); socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); byte byteMessage=new byte100; this.label1.Text=iep.ToString(); socket.Bind(iep); / do while(true) try socket.Listen(5); Socket newSocket=socket.Accept(); newSocket.Receive(byteMessage); string sTime = DateTime.Now.ToShortTimeString ( ) ; string msg=sTime+:+Message from:; msg+=newSocket.RemoteEndPoint.ToString()+Encoding.Default.GetString(byteMessage); this.listBox1.Items.Add(msg); catch(SocketException ex) this.label1.Text+=ex.ToString(); / while(byteMessage!=null); /开始监听 private void button1_Click(object sender, System.EventArgs e) try mythread = new Thread(new ThreadStart(BeginListen); mythread.Start(); catch(System.Exception er) MessageBox.Show(er.Message,完成,MessageBoxButtons.OK,MessageBoxIcon.Stop); 客户端:using System.Net;using System.Net.Sockets;using System.Text; private void button1_Click(object sender, System.EventArgs e) BeginSend(); private void BeginSend() string ip=this.txtip.Text; string port=this.txtport.Text; IPAddress serverIp=IPAddress.Parse(ip); int serverPort=Convert.ToInt32(port); IPEndPoint iep=new IPEndPoint(serverIp,serverPort); byte byteMessage; / do/ Socket socket=new Socket(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协议的接收端using System.Net.Sockets ; /使用到TcpListen类using System.Threading ; /使用到线程 using System.IO ; /使用到StreamReader类 int port = 8000; /定义侦听端口号 private Thread thThreadRead; /创建线程,用以侦听端口号,接收信息 private TcpListener tlTcpListen; /侦听端口号 private bool blistener = true; /设定标示位,判断侦听状态 private NetworkStream nsStream; /创建接收的基本数据流 private StreamReader srRead; private System.Windows.Forms.StatusBar statusBar1; private System.Windows.Forms.Button button1; private System.Windows.Forms.ListBox listBox1; /从网络基础数据流中读取数据 private TcpClient tcClient ; private void Listen ( ) try tlTcpListen = new TcpListener ( port ) ; /以8000端口号来初始化TcpListener实例 tlTcpListen.Start ( ) ; /开始监听 statusBar1.Text = 正在监听. ; tcClient = tlTcpListen.AcceptTcpClient ( ) ; /通过TCP连接请求 nsStream = tcClient.GetStream ( ) ; /获取用以发送、接收数据的网络基础数据流 srRead=new StreamReader(nsStream);/以得到的网络基础数据流来初始化StreamReader实例 statusBar1.Text = 已经连接!; while( blistener ) /循环侦听 string sMessage = srRead.ReadLine();/从网络基础数据流中读取一行数据 if ( sMessage = STOP ) /判断是否为断开TCP连接控制码 tlTcpListen.Stop(); /关闭侦听 nsStream.Close(); /释放资源 srRead.Close(); statusBar1.Text = 连接已经关闭! ; thThreadRead.Abort(); /中止线程 return; string sTime = DateTime.Now.ToShortTimeString ( ) ; /获取接收数据时的时间 listBox1.Items.Add ( sTime + + sMessage ) ; catch ( System.Security.SecurityException ) MessageBox.Show ( 侦听失败! , 错误 ) ; /开始监听 private void button1_Click(object sender, System.EventArgs e) thThreadRead = new Thread ( new ThreadStart ( Listen ) ); thThreadRead.Start();/启动线程 button1.Enabled=false; / 清理所有正在使用的资源。 protected override void Dispose( bool disposing ) try tlTcpListen.Stop(); /关闭侦听 nsStream.Close(); srRead.Close();/释放资源 thThreadRead.Abort();/中止线程 catch if( disposing ) if (components != null) components.Dispose(); base.Dispose( disposing ); TCP协议的发送端using System.Net.Sockets; /使用到TcpListen类using System.Threading; /使用到线程using System.IO; /使用到StreamWriter类using System.Net; /使用IPAddress类、IPHostEntry类等 private StreamWriter swWriter; /用以向网络基础数据流传送数据 private NetworkStream nsStream; /创建发送数据的网络基础数据流 private TcpClient tcpClient; private System.Windows.Forms.Button button1; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Button button2; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.StatusBar statusBar1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; /通过它实现向远程主机提出TCP连接申请 private bool tcpConnect = false; /定义标识符,用以表示TCP连接是否建立 /连接 private void button1_Click(object sender, System.EventArgs e) IPAddress ipRemote ; try ipRemote = IPAddress.Parse ( textBox1.Text ) ; catch /判断给定的IP地址的合法性 MessageBox.Show ( 输入的IP地址不合法! , 错误提示! ) ; return ; IPHostEntry ipHost ; try ipHost = Dns.Resolve ( textBox1.Text ) ; catch /判断IP地址对应主机是否在线 MessageBox.Show (远程主机不在线! , 错误提示! ) ; return ; string sHostName = ipHost.HostName ; try TcpClient tcpClient = new TcpClient(sHostName,8000);/对远程主机的8000端口提出TCP连接申请 nsStream = tcpClient.GetStream();/通过申请,并获取传送数据的网络基础数据流 swWriter = new StreamWriter(nsStream);/使用获取的网络基础数据流来初始化StreamWriter实例 button1.Enabled = false ; button2.Enabled = true ; tcpConnect = true ; statusBar1.Text = 已经连接! ; catch MessageBox.Show ( 无法和远程主机8000端口建立连接! , 错误提示! ) ; return ; /发送 private void button2_Click(object sender, System.EventArgs e) if (textBox2.Text !=) swWriter.WriteLine(textBox2.Text);/刷新当前数据流中的数据 swWriter.Flush(); else MessageBox.Show(发送信息不能为空!,错误提示!)
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025广东广州增城经济技术开发区园区发展局招聘特殊专业技术类聘员1人笔试模拟试题及答案解析
- 2025海南海口市总工会招聘下属事业单位人员2人(第1号)笔试模拟试题及答案解析
- 2025重庆市永川区陈食街道办事处公益性岗位招聘1人笔试参考题库附答案解析
- 护理专业毕业论文感想
- 2025广东清远市自然资源局清新分局招聘专项工作聘员2人笔试参考题库附答案解析
- 企业人力资源配置与薪酬福利管理作业指导书
- 农村建设项目工程承包责任书
- 2024年湖南省湘潭市《安全知识》资格考试模拟练习题及答案
- 2025云南楚雄州妇联招聘公益性岗位工作人员4人笔试备考题库及答案解析
- 金融投资分析基础指南
- 酒店装修工期管理措施
- 2025年注册测绘师测绘综合能力的真题卷(附答案)
- 2025-2030中国移动卫星终端设备行业发展分析及发展趋势与投资前景预测研究报告
- 智慧公交可行性研究报告
- 项目城市轨道交通风险管理与安全评估刘连珂
- 音乐演出活动场地使用协议
- 道路施工机械设备安全知识培训
- 销售人员廉洁自律心得体会
- 鲜奶运输规范管理制度
- AI在护理查房中的应用
- 2025版安全生产法培训
评论
0/150
提交评论