关于socket异步的问题,帮忙看看
服务端: private IPEndPoint MyServer;
private Socket sock;
private Socket handler;
private bool bb = true;
private void Form1_Load(object sender, EventArgs e)
{
try
{
MyServer = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 999);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(MyServer);
sock.Listen(50);
toolStripStatusLabel1.Text = "开始监听 ...";
sock.BeginAccept(new AsyncCallback(AcceptCallback), sock);
}
catch (Exception ee) { toolStripStatusLabel1.Text = ee.Message; }
Control.CheckForIllegalCrossThreadCalls = false;
}
private void targett()
{
if (handler.Connected)
{
toolStripStatusLabel1.Text = "与客户建立连接。";
while (bb)
{
Byte[] bbb = new Byte[64];
handler.Receive(bbb, bbb.Length, 0);
string ccc = System.Text.Encoding.BigEndianUnicode.GetString(bbb);
string x = "w";
int i = ccc.IndexOf(x);
if (i > 0)
{
saveUser(ccc);
}
richTextBox1.AppendText(ccc + "\r\n");
}
}
}
private void saveUser(string str)
{
...
}
private void AcceptCallback(IAsyncResult ar)
{
toolStripStatusLabel1.Text = "与客户建立连接!";
handler = ((Socket)ar.AsyncState).EndAccept(ar);
Thread thread = new Thread(new ThreadStart(targett));
thread.Start();
}
客户端:
private IPEndPoint MyServer;
private Socket sock;
private bool bb = true;
private void Form1_Load(object sender, EventArgs e)
{
try
{
MyServer = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 999);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Connect(MyServer);
toolStripStatusLabel1.Text = "连接成功!";
Thread thread = new Thread(new ThreadStart(targett));
thread.Start();
}
catch (Exception ee) { MessageBox.Show(ee.Message); }
Control.CheckForIllegalCrossThreadCalls = false;
}
private void targett()
{
while (bb)
{
Byte[] bbb = new Byte[640];
sock.Receive(bbb, bbb.Length, 0);
string aaaaa = System.Text.Encoding.BigEndianUnicode.GetString(bbb);
richTextBox1.AppendText(aaaaa);
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
Byte[] bytee = new Byte[640];
string send = richTextBox2.Text + "\r\n";
bytee = System.Text.Encoding.BigEndianUnicode.GetBytes(send.ToCharArray());
sock.Send(bytee, bytee.Length, 0);
}
catch { MessageBox.Show("连接尚未建立! 无法发送!"); }
}
我想在客户端发送一串字符到服务端,服务端判断如果字符中有"w",就执行saveUser(),为什么我发送例如"weeeeee"他还是不执行呢,请大家帮忙看看代码有什么问题。