我现在正学习Socket异步通信,准备做一个winform聊天工具的实例,代码基本上都是按照MSDN上面的示例写的,现在遇到的问题是客户端和服务端脸上之后只能收发一条信息,大概的流程是这样的:服务端发送信息——客户端接受信息,并将受到的信息回发给服务端——服务端接收客户端发来的信息,然后再发送消息就没反应了,程序也不死,就是啥都不干死,就是啥都不干,求给位帮帮忙啊
***服务端***
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;namespace TcpServer
{
/// <summary>
/// Socket异步通信服务器端代码
/// </summary>
public partial class TcpServer : Form
{
public TcpServer()
{
InitializeComponent();
} #region 变量定义区
IPAddress ip = IPAddress.Parse("192.168.1.57");
int port = 8000;
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); StateObject state = new StateObject(); Thread connThread; ManualResetEvent allDone = new ManualResetEvent(false);
ManualResetEvent sendDone = new ManualResetEvent(false);
ManualResetEvent receiveDone = new ManualResetEvent(false);
#endregion #region 连接
/// <summary>
/// 监听
/// </summary>
public void Accept()
{
IPEndPoint ipep = new IPEndPoint(ip, port); sock.Bind(ipep);
sock.Listen(1); AddMsg(txtNotice, "等待一个有效连接");
while (true)
{
allDone.Reset();
sock.BeginAccept(new AsyncCallback(AcceptCallBack), sock);
allDone.WaitOne();
}
}
/// <summary>
/// 监听回调函数
/// </summary>
/// <param name="iar"></param>
public void AcceptCallBack(IAsyncResult iar)
{
allDone.Set(); Socket server = (Socket)iar.AsyncState;
Socket client = server.EndAccept(iar); IPEndPoint cipep = (IPEndPoint)client.RemoteEndPoint;
IPAddress cip = cipep.Address; AddItem(cip.ToString());
txtNotice.Clear();
AddMsg(txtNotice, "有一个客户端已经连接过来"); state.workSocket = client; // 将有效的客户端连接client赋给state实例中的workSocket
while (client.Connected == true)
{
try
{
Receive();
}
catch
{ }
}
}
#endregion #region 接收信息
/// <summary>
/// 接收信息
/// </summary>
public void Receive()
{
state.workSocket.BeginReceive(state.data, 0, StateObject.bufferSize, 0, new AsyncCallback(ReadCallBack), state); //静态变量bufferSize不能用实例访问
receiveDone.WaitOne();
}
/// <summary>
/// 接收信息回调函数
/// </summary>
/// <param name="iar"></param>
public void ReadCallBack(IAsyncResult iar)
{
StateObject stateobject = (StateObject)iar.AsyncState; //?无法将类型System.Net.Sockets强制转换为System.TcpServer.StateObject类型
Socket handler = state.workSocket; int bytesRead = handler.EndReceive(iar);
try
{
if (bytesRead > 0)
{
string contentstr = ""; //声明一个字符串变量,用于存储接收到的数据
contentstr += Encoding.UTF8.GetString(state.data, 0, state.data.Length);
AddMsg(recTxt, contentstr);
Send(handler, state.data.ToString()); //回发给客户端
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
receiveDone.Set();
}
#endregion #region 发送信息
/// <summary>
/// 发送信息
/// </summary>
/// <param name="sock"></param>
/// <param name="str"></param>
public void Send(Socket sock, string str)
{
if (sock.Connected == true)
{
if (str != null)
{
state.data = Encoding.UTF8.GetBytes("服务端:\r\t" + DateTime.Now.ToString() + "\r\n" + str + "\r\n");
sock.BeginSend(state.data, 0, state.data.Length, 0, new AsyncCallback(SendCallBack), state);
}
else
{
MessageBox.Show("不能发送空消息");
}
}
else
{
MessageBox.Show("尚未建立连接,不能发送消息");
}
sendDone.WaitOne();
}
/// <summary>
/// 发送信息回调函数
/// </summary>
/// <param name="iar"></param>
public void SendCallBack(IAsyncResult iar)
{
try
{
Socket handler = (Socket)iar.AsyncState;
int send = handler.EndSend(iar);
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
sendDone.Set();
}
#endregion #region 文本框
/// <summary>
/// 文本框操作函数
/// </summary>
/// <param name="txtBox"></param>
/// <param name="str"></param>
public void AddMsg(TextBox txtBox, string str)
{
txtBox.Text += str;
}
public void AddItem(string strItem)
{
txtClient.Text += strItem + "\r\n";
}
#endregion
}
}
***客户端***
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.Net;namespace TcpClient
{
public partial class TcpClient : Form
{
public TcpClient()
{
InitializeComponent();
}
#region 变量定义区
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); StateObject state = new StateObject(); //一个容器类实例 Thread connThread; ManualResetEvent connectDone = new ManualResetEvent(false);
ManualResetEvent sendDone = new ManualResetEvent(false);
ManualResetEvent receiveDone = new ManualResetEvent(false);
#endregion #region 连接
public void Connect()
{
IPAddress ip = IPAddress.Parse(txtIP.Text);
int port = Convert.ToInt32(txtPort.Text);
IPEndPoint ipep = new IPEndPoint(ip, port); sock.BeginConnect(ipep, new AsyncCallback(ConnectCallBack), sock);
connectDone.WaitOne();
}
public void ConnectCallBack(IAsyncResult iar)
{
Socket client = (Socket)iar.AsyncState;
client.EndConnect(iar);
connectDone.Set();
AddMsg("已成功连接服务器\r\n"); state.workSocket = client; Receive();
}
#endregion #region 接收信息
public void Receive()
{
state.workSocket.BeginReceive(state.data, 0, StateObject.bufferSize, 0, new AsyncCallback(ReadCallBack), state); //静态变量bufferSize不能用实例访问
receiveDone.WaitOne();
}
public void ReadCallBack(IAsyncResult iar)
{
StateObject state = (StateObject)iar.AsyncState;
Socket handler = state.workSocket; try
{
int bytesRead = handler.EndReceive(iar); if (bytesRead > 0)
{
string contentstr = ""; //声明一个字符串变量,用于存储接收到的数据
contentstr += Encoding.UTF8.GetString(state.data, 0, state.data.Length);
AddMsg(contentstr);
Send(contentstr); //回发给服务端
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
receiveDone.Set();
}
#endregion #region 发送信息
public void Send(string str)
{
sock = state.workSocket;
state.data = Encoding.UTF8.GetBytes("客户端:\r\t" + DateTime.Now.ToString() + "\r\n" + str + "\r\n"); sock.BeginSend(state.data, 0, state.data.Length, 0, new AsyncCallback(SendCallBack), sock); sendTxt.Clear();
sendDone.WaitOne();
}
public void SendCallBack(IAsyncResult iar)
{
Socket sock = (Socket)iar.AsyncState;
int send = sock.EndSend(iar); sendDone.Set();
}
#endregion #region 文本框
public void AddMsg(string str)
{
recTxt.Text += str;
}
#endregion
}
}
***服务端***
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;namespace TcpServer
{
/// <summary>
/// Socket异步通信服务器端代码
/// </summary>
public partial class TcpServer : Form
{
public TcpServer()
{
InitializeComponent();
} #region 变量定义区
IPAddress ip = IPAddress.Parse("192.168.1.57");
int port = 8000;
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); StateObject state = new StateObject(); Thread connThread; ManualResetEvent allDone = new ManualResetEvent(false);
ManualResetEvent sendDone = new ManualResetEvent(false);
ManualResetEvent receiveDone = new ManualResetEvent(false);
#endregion #region 连接
/// <summary>
/// 监听
/// </summary>
public void Accept()
{
IPEndPoint ipep = new IPEndPoint(ip, port); sock.Bind(ipep);
sock.Listen(1); AddMsg(txtNotice, "等待一个有效连接");
while (true)
{
allDone.Reset();
sock.BeginAccept(new AsyncCallback(AcceptCallBack), sock);
allDone.WaitOne();
}
}
/// <summary>
/// 监听回调函数
/// </summary>
/// <param name="iar"></param>
public void AcceptCallBack(IAsyncResult iar)
{
allDone.Set(); Socket server = (Socket)iar.AsyncState;
Socket client = server.EndAccept(iar); IPEndPoint cipep = (IPEndPoint)client.RemoteEndPoint;
IPAddress cip = cipep.Address; AddItem(cip.ToString());
txtNotice.Clear();
AddMsg(txtNotice, "有一个客户端已经连接过来"); state.workSocket = client; // 将有效的客户端连接client赋给state实例中的workSocket
while (client.Connected == true)
{
try
{
Receive();
}
catch
{ }
}
}
#endregion #region 接收信息
/// <summary>
/// 接收信息
/// </summary>
public void Receive()
{
state.workSocket.BeginReceive(state.data, 0, StateObject.bufferSize, 0, new AsyncCallback(ReadCallBack), state); //静态变量bufferSize不能用实例访问
receiveDone.WaitOne();
}
/// <summary>
/// 接收信息回调函数
/// </summary>
/// <param name="iar"></param>
public void ReadCallBack(IAsyncResult iar)
{
StateObject stateobject = (StateObject)iar.AsyncState; //?无法将类型System.Net.Sockets强制转换为System.TcpServer.StateObject类型
Socket handler = state.workSocket; int bytesRead = handler.EndReceive(iar);
try
{
if (bytesRead > 0)
{
string contentstr = ""; //声明一个字符串变量,用于存储接收到的数据
contentstr += Encoding.UTF8.GetString(state.data, 0, state.data.Length);
AddMsg(recTxt, contentstr);
Send(handler, state.data.ToString()); //回发给客户端
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
receiveDone.Set();
}
#endregion #region 发送信息
/// <summary>
/// 发送信息
/// </summary>
/// <param name="sock"></param>
/// <param name="str"></param>
public void Send(Socket sock, string str)
{
if (sock.Connected == true)
{
if (str != null)
{
state.data = Encoding.UTF8.GetBytes("服务端:\r\t" + DateTime.Now.ToString() + "\r\n" + str + "\r\n");
sock.BeginSend(state.data, 0, state.data.Length, 0, new AsyncCallback(SendCallBack), state);
}
else
{
MessageBox.Show("不能发送空消息");
}
}
else
{
MessageBox.Show("尚未建立连接,不能发送消息");
}
sendDone.WaitOne();
}
/// <summary>
/// 发送信息回调函数
/// </summary>
/// <param name="iar"></param>
public void SendCallBack(IAsyncResult iar)
{
try
{
Socket handler = (Socket)iar.AsyncState;
int send = handler.EndSend(iar);
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
}
sendDone.Set();
}
#endregion #region 文本框
/// <summary>
/// 文本框操作函数
/// </summary>
/// <param name="txtBox"></param>
/// <param name="str"></param>
public void AddMsg(TextBox txtBox, string str)
{
txtBox.Text += str;
}
public void AddItem(string strItem)
{
txtClient.Text += strItem + "\r\n";
}
#endregion
}
}
***客户端***
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.Net;namespace TcpClient
{
public partial class TcpClient : Form
{
public TcpClient()
{
InitializeComponent();
}
#region 变量定义区
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); StateObject state = new StateObject(); //一个容器类实例 Thread connThread; ManualResetEvent connectDone = new ManualResetEvent(false);
ManualResetEvent sendDone = new ManualResetEvent(false);
ManualResetEvent receiveDone = new ManualResetEvent(false);
#endregion #region 连接
public void Connect()
{
IPAddress ip = IPAddress.Parse(txtIP.Text);
int port = Convert.ToInt32(txtPort.Text);
IPEndPoint ipep = new IPEndPoint(ip, port); sock.BeginConnect(ipep, new AsyncCallback(ConnectCallBack), sock);
connectDone.WaitOne();
}
public void ConnectCallBack(IAsyncResult iar)
{
Socket client = (Socket)iar.AsyncState;
client.EndConnect(iar);
connectDone.Set();
AddMsg("已成功连接服务器\r\n"); state.workSocket = client; Receive();
}
#endregion #region 接收信息
public void Receive()
{
state.workSocket.BeginReceive(state.data, 0, StateObject.bufferSize, 0, new AsyncCallback(ReadCallBack), state); //静态变量bufferSize不能用实例访问
receiveDone.WaitOne();
}
public void ReadCallBack(IAsyncResult iar)
{
StateObject state = (StateObject)iar.AsyncState;
Socket handler = state.workSocket; try
{
int bytesRead = handler.EndReceive(iar); if (bytesRead > 0)
{
string contentstr = ""; //声明一个字符串变量,用于存储接收到的数据
contentstr += Encoding.UTF8.GetString(state.data, 0, state.data.Length);
AddMsg(contentstr);
Send(contentstr); //回发给服务端
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
receiveDone.Set();
}
#endregion #region 发送信息
public void Send(string str)
{
sock = state.workSocket;
state.data = Encoding.UTF8.GetBytes("客户端:\r\t" + DateTime.Now.ToString() + "\r\n" + str + "\r\n"); sock.BeginSend(state.data, 0, state.data.Length, 0, new AsyncCallback(SendCallBack), sock); sendTxt.Clear();
sendDone.WaitOne();
}
public void SendCallBack(IAsyncResult iar)
{
Socket sock = (Socket)iar.AsyncState;
int send = sock.EndSend(iar); sendDone.Set();
}
#endregion #region 文本框
public void AddMsg(string str)
{
recTxt.Text += str;
}
#endregion
}
}
应该准备4个套接字 也就是socket
你这样分配了 再试试