// 网络调试:打开服务器 private void net_bt_opennet_Click(object sender, EventArgs e) { //检查IP地址输入格式是否正确 String regx = @"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))"; System.Text.RegularExpressions.Regex check = new System.Text.RegularExpressions.Regex(regx); if (!check.IsMatch(net_tb_localip.Text)) { MessageBox.Show("本地IP地址输入错误,请重新输入!", "警告"); return; } //检查端口号是否为空 if (net_tb_localport.Text.Equals("")) { MessageBox.Show("请输入本地端口号!", "警告"); return; } //建立Socket连接 try { if (hostSocket == null) { hostSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); hostSocket.Bind(new IPEndPoint(IPAddress.Parse(net_tb_localip.Text), Convert.ToInt32(net_tb_localport.Text))); //设置 监听队列 长度为50(同时能够处理 50个连接请求) hostSocket.Listen(50); showTip1.Text = "服务器已启动,开始监听"; //开始接受客户端连接请求 //HostSocket.BeginAccept(new AsyncCallback(ClientAccepted), HostSocket); isWatch = true; threadWatch = new Thread(ClientAccepted0); threadWatch.IsBackground = true; threadWatch.Start(); showTip1.Text = "服务器已启动,开始接收数据"; showTip2.Text = "建立连接:0"; net_bt_opennet.Enabled = false; net_bt_closenet.Enabled = true; SystemConfig.WriteConfigData("LocalPort", net_tb_localport.Text.Trim()); SystemConfig.WriteConfigData("LocalIP", net_tb_localip.Text.Trim()); net_tb_localip.Enabled = false; net_tb_localport.Enabled = false; net_btnSend.Enabled = true; net_btnSendAll.Enabled = true; net_tx_send.Enabled = true; hasOpen = true; MainForms.ServerChange = true; } } catch (Exception) { MessageBox.Show("本地IP地址错误或端口已被占用!", "警告"); return; } }
private NetDebugForm() { InitializeComponent(); net_tb_localport.Text = SystemConfig.GetConfigData("LocalPort", string.Empty); net_tb_localip.Text = SystemConfig.GetConfigData("LocalIP", string.Empty); }