欢迎来到天天文库
浏览记录
ID:15418405
大小:204.50 KB
页数:8页
时间:2018-08-03
《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;//添加命名空间namesp
2、ace WFAsynSocket{ public partial class Form1 : Form { Thread LisThread; Socket LisSocket; Socket newSocket; EndPoint point; string strmes = String.Empty; int port = 8000;//定义侦听端口号 public Form1() { Initia
3、lizeComponent(); } private void btn_Listen_Click(object sender, EventArgs e) { LisThread = new Thread(new ThreadStart(BeginListern));//开线程执行BeginListern方法 LisThread.Start();//线程开始执行 } public IPAddress GetIP() { /*获
4、取本地服务器的ip地址 */ IPHostEntry iep = Dns.GetHostEntry(Dns.GetHostName()); IPAddress ip = iep.AddressList[0]; return ip; } public void BeginListern() { LisSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
5、 ProtocolType.Tcp);//实例化Socket IPAddress ServerIp = GetIP();/*获取本地服务器的ip地址 */ IPEndPoint iep = new IPEndPoint(ServerIp, port); LisSocket.Bind(iep); /*将Socket绑定ip */ toolStripStatusLabel1.Text = iep.ToString() + "正在监听"; LisSoc
6、ket.Listen(50); //Socket开始监听 newSocket = LisSocket.Accept();//获取连接请求的Socket /*接收客户端Socket所发的信息 */ while (true) { try { byte[] byteMessage = new byte[100];
7、 newSocket.Receive(byteMessage);//接收信息 MessageBox.Show(Encoding.Default.GetString(byteMessage)); Control.CheckForIllegalCrossThreadCalls = false; point = newSocket.RemoteEndPoint;//获取客户端的Socket的相关信息
8、 IPEndPoint
此文档下载收益归作者所有