private void ReceiveHandle() { //接收数据处理线程 string msg; byte[] data = new byte[1024]; Control.CheckForIllegalCrossThreadCalls = false; //跨线程调用控件 while (RunningFlag) { try { if (mySocket == null || mySocket.Available < 1) { continue; } int rlen = mySocket.ReceiveFrom(data, ref RemotePoint); msg = Encoding.Default.GetString(data, 0, rlen); string seversay = HexToAscii.AsciiToHex(msg); seversay = Regex.Replace(seversay, @"(\d{2}(?!$))", "$1 "); rtxChatInfo.AppendText(DateTime.Now.ToString()); rtxChatInfo.AppendText(" 服务器说:\n"); rtxChatInfo.AppendText(seversay + " " + "[" + rlen + "]" + "\n"); //下拉框 rtxChatInfo.SelectionStart = rtxChatInfo.Text.Length; rtxChatInfo.Focus(); rtxSendMessage.Focus(); } catch { //MessageBox.Show("远程主机无响应"); } } }
public void SendMessage() { try { if (rtxSendMessage.Text.Trim() != "") // 发送消息不为空 { byte[] data = HexToAscii.HexToAsci(rtxSendMessage.Text); if (data != null) { //得到客户机IP IPEndPoint ipep = new IPEndPoint(getValidIP(txtServerIp.Text), getValidPort(txtPort.Text)); RemotePoint = (EndPoint)(ipep); mySocket.SendTo(data, data.Length, SocketFlags.None, RemotePoint); rtxChatInfo.AppendText(DateTime.Now.ToString()); // 显示框 rtxChatInfo rtxChatInfo.AppendText(" 客户端说: \n"); rtxChatInfo.AppendText(rtxSendMessage.Text + "\n"); //rtxSendMessage.Clear(); } //下拉框 rtxChatInfo.SelectionStart = rtxChatInfo.Text.Length; rtxChatInfo.Focus(); rtxSendMessage.Focus(); } else { MessageBox.Show("信息不能为空!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); txtServerIp.Focus(); return; } } catch { txtServerIp.Enabled = true; btnConnect.Enabled = true; MessageBox.Show("服务器连失败!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Text = "连接失败……"; return; } }