欢迎来到天天文库
浏览记录
ID:14265346
大小:204.50 KB
页数:8页
时间:2018-07-27
《socket服务器与客户端双向通信实例》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、Socket服务器与客户端双向通信实例using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Net;using System.Net.Sockets;//添加命名空间using System.Threading;//添加命名空间namespace WF
2、AsynSocket{ public partial class Form1 : Form { Thread LisThread; Socket LisSocket; Socket newSocket; EndPoint point; string strmes = String.Empty; int port = 8000;//定义侦听端口号 public Form1() { InitializeComponen
3、t(); } private void btn_Listen_Click(object sender, EventArgs e) { LisThread = new Thread(new ThreadStart(BeginListern));//开线程执行BeginListern方法 LisThread.Start();//线程开始执行 } public IPAddress GetIP() { /*获取本地服务器的ip地址 */
4、 IPHostEntry iep = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ip = iep.AddressList[0]; return ip; } public void BeginListern() { LisSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//实例化
5、Socket IPAddress ServerIp = GetIP();/*获取本地服务器的ip地址 */ IPEndPoint iep = new IPEndPoint(ServerIp, port); LisSocket.Bind(iep); /*将Socket绑定ip */ toolStripStatusLabel1.Text = iep.ToString() + "正在监听"; LisSocket.Listen(50); //Socket开始监听
6、 newSocket = LisSocket.Accept();//获取连接请求的Socket /*接收客户端Socket所发的信息 */ while (true) { try { byte[] byteMessage = new byte[100]; newSocket.Re
7、ceive(byteMessage);//接收信息 MessageBox.Show(Encoding.Default.GetString(byteMessage)); Control.CheckForIllegalCrossThreadCalls = false; point = newSocket.RemoteEndPoint;//获取客户端的Socket的相关信息 IPEndPoint
此文档下载收益归作者所有