C# Socket异步客户端假死 求解 代码如下

qwww450728 2011-08-30 11:09:11
//通用类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace ServerForm.Comm
{
class StateObject
{
internal Socket workStock = null;
internal const int BufferSize = 1024;
internal byte[] buffer = new byte[1024];
internal StringBuilder stringbuilder = new StringBuilder();
}
}

//控件
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.txbServerIP = new System.Windows.Forms.TextBox();
this.txbPort = new System.Windows.Forms.TextBox();
this.rhbSendMessage = new System.Windows.Forms.RichTextBox();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.lsbClientSate = new System.Windows.Forms.ListBox();
this.btnRequireConnect = new System.Windows.Forms.Button();
this.btnSendMessage = new System.Windows.Forms.Button();
this.btnDisConnect = new System.Windows.Forms.Button();
this.rhbReciveMessages = new System.Windows.Forms.RichTextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.SuspendLayout();

//主程序代码
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;
using ServerForm.Comm;

namespace ServerForm
{
public partial class AsynClientForm : Form
{
public AsynClientForm()
{
InitializeComponent();
}

#region 跨线程调用控件
private delegate void UpdateUIDelegate(string msg);
/// <summary>
/// 添加状态信息
/// </summary>
/// <param name="msg">状态</param>
private void UpdateUI(string msg)
{
if (lsbClientSate.InvokeRequired)
{
UpdateUIDelegate _myinvoke = new UpdateUIDelegate(UpdateUI);
lsbClientSate.Invoke(_myinvoke, new object[] { msg });
}
else
{
lsbClientSate.Items.Add(msg);
}

}
/// <summary>
///显示接收到的信息
/// </summary>
/// <param name="msg"></param>
private void AddMessageUI(string msg)
{
if (rhbReciveMessages.InvokeRequired)
{
UpdateUIDelegate _myinvoke = new UpdateUIDelegate(UpdateUI);
rhbReciveMessages.Invoke(_myinvoke, new object[] { msg });
}
else
{
rhbReciveMessages.AppendText(msg);
}
}

#endregion


#region 私有的
private IPAddress myIP = IPAddress.Parse("127.0.0.1");
private IPEndPoint MyServer;
private Socket mySocket;
private static ManualResetEvent connectReset = new ManualResetEvent(false);
private static ManualResetEvent sendReset = new ManualResetEvent(false);

/// <summary>
/// 连接回调函数
/// </summary>
/// <param name="ar"></param>
private void ConnectCallback(IAsyncResult ar)
{
try
{
Socket clientSocket = (Socket)ar.AsyncState;
clientSocket.EndConnect(ar);
try
{
byte[] byteData = System.Text.Encoding.BigEndianUnicode.GetBytes("准备完毕,可以通话!");
//发送数据
mySocket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), mySocket);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
UpdateUI("主机" + txbServerIP.Text + "端口" + txbPort.Text + "建立连接");

Thread thread = new Thread(new ThreadStart(Target));
thread.Start();
//有信号--激活WaitOne() 方法
connectReset.Set();//有信号--激活WaitOne() 方法
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

/// <summary>
///开始 调用接收回调函数
/// </summary>
private void Target()
{
try
{
StateObject state = new StateObject();
state.workStock = mySocket;
mySocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReciveCallbck), state);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

/// <summary>
/// 接收回调函数
/// </summary>
/// <param name="ar"></param>
private void ReciveCallbck(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket clientSocket = state.workStock;
int bytesRead = clientSocket.EndReceive(ar);
state.stringbuilder.Append(System.Text.Encoding.BigEndianUnicode.GetString(state.buffer, 0, bytesRead));
string strContent = state.stringbuilder.ToString();
state.stringbuilder.Remove(0, strContent.Length);
AddMessageUI(strContent + "\r\n");
//rhbReciveMessages.AppendText(strContent);
//重新开始读取数据
clientSocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

/// <summary>
///发送回调 终止
/// </summary>
/// <param name="ar"></param>
private void SendCallback(IAsyncResult ar)
{
try
{
Socket clintSocket = (Socket)ar.AsyncState;
//有信号
sendReset.Set();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

/// <summary>
/// 开始接收
/// </summary>
private void BeginReceive()
{
StateObject state = new StateObject();
state.workStock = mySocket;
mySocket.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}

/// <summary>
/// 读取回调
/// </summary>
/// <param name="ar"></param>
private void ReadCallback(IAsyncResult ar)
{
StateObject state = (StateObject)ar.AsyncState;
Socket tt = state.workStock;
int bytesRead = mySocket.EndReceive(ar);
state.stringbuilder.Append(System.Text.Encoding.BigEndianUnicode.GetString(state.buffer, 0, bytesRead));
string strContent = state.stringbuilder.ToString();
state.stringbuilder.Remove(0, strContent.Length);
AddMessageUI(strContent + "\r\n");
//rhbReciveMessages.AppendText(strContent);
//重新开始读取数据
tt.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}

#endregion

//请求连接
private void btnRequireConnect_Click(object sender, EventArgs e)
{
try
{
IPHostEntry myHost = new IPHostEntry();
myHost = Dns.GetHostEntry(txbServerIP.Text); //Dns.GetHostByName(txbServerIP.Text);
string strIP = myHost.AddressList[0].ToString();
myIP = IPAddress.Parse(strIP);
}
catch
{
MessageBox.Show("无法转化IP");
}
try
{
MyServer = new IPEndPoint(myIP, Int32.Parse(txbPort.Text));
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
mySocket.BeginConnect(MyServer, new AsyncCallback(ConnectCallback), mySocket);
connectReset.WaitOne(); //无信号时挂起线程--Set() 可以激活--挂起主线程要启用新线程
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

//发送信息
private void btnSendMessage_Click(object sender, EventArgs e)
{
try
{
byte[] byteData = System.Text.Encoding.BigEndianUnicode.GetBytes(rhbSendMessage.Text);
rhbSendMessage.Text = string.Empty;
//发送数据
mySocket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), mySocket);
}
catch (SocketException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

//断开连接
private void btnDisConnect_Click(object sender, EventArgs e)
{
try
{
mySocket.Shutdown(SocketShutdown.Both);
UpdateUI("主机" + txbServerIP.Text + "端口" + txbPort.Text + "监听停止");
}
catch
{
MessageBox.Show("监听尚未开始关闭无效");
}
}

//退出
private void AsynClientForm_FormClosing(object sender, FormClosingEventArgs e)
{
Environment.Exit(0);
}

}
}
...全文
131 3 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
qwww450728 2011-08-30
  • 打赏
  • 举报
回复
你说的太笼统了吧
a82344626 2011-08-30
  • 打赏
  • 举报
回复
用多线程
你现在所有操作都 在主线程里了当然会卡界面了!
Just4life 2011-08-30
  • 打赏
  • 举报
回复
应该在线程里面来做Socket的相关事情

111,097

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧