c# - TCP 套接字客户端\服务器请求响应
问题描述
我正在开发一个 .Net 4.5.2 windows TCP socket master\client 消息传递解决方案。该解决方案在很大程度上是有效的;however I need the server to send a response message back to the client when the send button is selected. 选择“连接”按钮时,Master确实成功地将响应消息发送回客户端。I have made numerous attempts to send the response message back to the client application from the master when the send button is selected, but I have been unable to make it work. 我正在寻求一些帮助,让我再次前进。不想继续旋转我的轮子并且没有进展。在此先感谢您的帮助。请在下面找到服务器和客户端解决方案:
服务器代码:
public partial class ServerForm : Form
{
private Socket serverSocket;
private Socket clientSocket; // We will only accept one socket.
private byte[] buffer;
public ServerForm()
{
InitializeComponent();
StartServer();
}
private static void ShowErrorDialog(string message)
{
MessageBox.Show(message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void StartServer()
{
try
{
IPAddress ipAddress = IPAddress.Parse("192.168.1.124");
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(ipAddress, 4545));
serverSocket.Listen(10);
serverSocket.BeginAccept(AcceptCallback, null);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
private void AcceptCallback(IAsyncResult AR)
{
try
{
clientSocket = serverSocket.EndAccept(AR);
buffer = new byte[clientSocket.ReceiveBufferSize];
var sendData = Encoding.ASCII.GetBytes("Hello");
clientSocket.BeginSend(sendData, 0, sendData.Length, SocketFlags.None, SendCallback, null);
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, null);
serverSocket.BeginAccept(AcceptCallback, null);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
private void SendCallback(IAsyncResult AR)
{
try
{
clientSocket.EndSend(AR);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
private void ReceiveCallback(IAsyncResult AR)
{
try
{
Socket current = (Socket)AR.AsyncState;
int received = clientSocket.EndReceive(AR);
if (received == 0)
{
return;
}
PersonPackage person = new PersonPackage(buffer);
SubmitPersonToDataGrid(person);
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, null);
//Added BeginSend which answered my question. Simple enough fix. Thanks for looking...
byte[] sendData = Encoding.ASCII.GetBytes(person.Name);
clientSocket.BeginSend(sendData, 0, sendData.Length, SocketFlags.None, SendCallback, null);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
客户代码:
public partial class ClientForm : Form
{
private Socket clientSocket;
private byte[] buffer;
public ClientForm()
{
InitializeComponent();
}
private static void ShowErrorDialog(string message)
{
MessageBox.Show(message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
private void ReceiveCallback(IAsyncResult AR)
{
try
{
int received = clientSocket.EndReceive(AR);
if (received == 0)
{
return;
}
string message = Encoding.ASCII.GetString(buffer).TrimEnd('\0');
Invoke((Action) delegate
{
textBoxEmployee.Text = string.Empty;
textBoxEmployee.Text = "Server says: " + message + " Paul";
});
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, null);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
private void ConnectCallback(IAsyncResult AR)
{
try
{
clientSocket.EndConnect(AR);
UpdateControlStates(true);
buffer = new byte[clientSocket.ReceiveBufferSize];
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, null);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
private void SendCallback(IAsyncResult AR)
{
try
{
clientSocket.EndSend(AR);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
private void UpdateControlStates(bool toggle)
{
Invoke((Action)delegate
{
buttonSend.Enabled = toggle;
buttonConnect.Enabled = !toggle;
labelIP.Visible = textBoxAddress.Visible = !toggle;
});
}
private void buttonSend_Click(object sender, EventArgs e)
{
try
{
PersonPackage person = new PersonPackage(checkBoxMale.Checked, (ushort)numberBoxAge.Value, textBoxEmployee.Text);
byte[] buffer = person.ToByteArray();
clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, SendCallback, null);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
UpdateControlStates(false);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
UpdateControlStates(false);
}
}
private void buttonConnect_Click(object sender, EventArgs e)
{
try
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect to the specified host.
var endPoint = new IPEndPoint(IPAddress.Parse(textBoxAddress.Text), 4545);
clientSocket.BeginConnect(endPoint, ConnectCallback, null);
}
catch (SocketException ex)
{
ShowErrorDialog(ex.Message);
}
catch (ObjectDisposedException ex)
{
ShowErrorDialog(ex.Message);
}
}
}
解决方案
发现问题。添加BeginSend
到服务器SendCallBack
方法。代码已更新并且可以工作...
推荐阅读
- python - 无法在同一目录和包中导入模块
- java - “java.io.FileNotFoundException:没有文件匹配规范”虽然文件已成功写入
- linux - 我的 Vncserver 设置有什么问题?
- java - 定义单例与在接口中声明
- ios - 如何修复 Xcode 10 中的小部件库,因为它在选择一个小部件 ios 后隐藏起来
- javascript - 缺少)在脚本管理器的参数列表错误之后
- ios - 如何删除左 UIBarButtonItem 的填充?
- javascript - 如何将原始数据主体添加到 axios 请求?
- jetty - 码头空闲超时异常
- artifactory - 人工可信存储库已损坏