I have a winform server and a client programs. both are connected, the client can send data to server and the server receives. but when the server sends data, the client cannot receive.
here is the code for client to receive data:
//RECIEVE PART
private Socket _clientSocket; // We will only accept one socket
private byte[] _buffer;
public Form1()
{
InitializeComponent();
StartRecieve();
}
#region Receiving Data
private void StartRecieve()
{
try
{
_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// _serverSocket.Bind(new IPEndPoint(IPAddress.Any, 3333));
_serverSocket.Listen(10);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AcceptCallback(IAsyncResult AR)
{
try
{
_clientSocket = _serverSocket.EndAccept(AR);
_buffer = new byte[_clientSocket.ReceiveBufferSize];
_clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ReceiveCallback(IAsyncResult AR)
{
try
{
int received = _clientSocket.EndReceive(AR);
Array.Resize(ref _buffer, received); // Shrink buffer to trim null characters
string text = Encoding.ASCII.GetString(_buffer);
Array.Resize(ref _buffer, _clientSocket.ReceiveBufferSize); // Regrow buffer
//AppendToTextBox(text);
MessageBox.Show(text);
// Start receiving data again
_clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion
#region Display
/// <summary>
/// Provides a thread safe way to append text to the textbox
/// </summary>
private void AppendToTextBox(string text)
{
MethodInvoker invoker = new MethodInvoker(delegate
{
// Add two new lines afterwards
TboxDisp.Text += text + "\r\n" + "\r\n";
});
this.Invoke(invoker);
}
#endregion
//Connection Part
private void BtnConnect_Click(object sender, EventArgs e)
{
try
{
string ip = TboxIP.Text;
int port = int.Parse(TboxPort.Text);
_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect to the host
_clientSocket.BeginConnect(new IPEndPoint(IPAddress.Parse(ip), port),
new AsyncCallback(ConnectCallback), null);
if (SocketConnected(_clientSocket) == true)
{
lblstatus.Text = "Establishing Connection to " + ip;
lblstatus2.Text = "Connection Established";
}
// Connect1(ip, port);
}
catch (SystemException ex)
{
MessageBox.Show(ex.Message);
}
}
//ends bending requests
private void ConnectCallback(IAsyncResult AR)
{
try
{
_clientSocket.EndConnect(AR);
EnableSearchButton();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
//Enables the button search
private void EnableSearchButton()
{
MethodInvoker invoker = new MethodInvoker(delegate
{
BtnSearch.Enabled = true;
});
this.Invoke(invoker);
}
#endregion
private void BtnSearch_Click(object sender, EventArgs e)
{
try
{
// Serialize the textBoxes text before sending
// byte[] buffer = Encoding.ASCII.GetBytes(textBox.Text);
string command = "HELOTAGP/1.1\n";
byte[] buffer = Encoding.ASCII.GetBytes(command);
_clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallback), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
//Ends pending asynchronous send
private void SendCallback(IAsyncResult AR)
{
try
{
_clientSocket.EndSend(AR);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
and the complete server code (receive + sending) is :
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 void StartServer()
{
try
{
_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_serverSocket.Bind(new IPEndPoint(IPAddress.Any, 3333));
_serverSocket.Listen(10);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AcceptCallback(IAsyncResult AR)
{
try
{
_clientSocket = _serverSocket.EndAccept(AR);
_buffer = new byte[_clientSocket.ReceiveBufferSize];
_clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ReceiveCallback(IAsyncResult AR)
{
try
{
int received = _clientSocket.EndReceive(AR);
Array.Resize(ref _buffer, received); // Shrink buffer to trim null characters
string text = Encoding.ASCII.GetString(_buffer);
Array.Resize(ref _buffer, _clientSocket.ReceiveBufferSize); // Regrow buffer
AppendToTextBox(text);
// Start receiving data again
_clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
/// <summary>
/// Provides a thread safe way to append text to the textbox
/// </summary>
private void AppendToTextBox(string text)
{
MethodInvoker invoker = new MethodInvoker(delegate
{
// Add two new lines afterwards
textBox.Text += text + "\r\n" + "\r\n";
});
this.Invoke(invoker);
}
//sending data
private void BtnSend_Click(object sender, EventArgs e)
{
try
{
// Serialize the textBoxes text before sending
string command = "Test";
byte[] buffer = Encoding.ASCII.GetBytes(command);
_clientSocket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallback), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void SendCallback(IAsyncResult AR)
{
try
{
_clientSocket.EndSend(AR);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
the server receives the data correctly, but i don't know why the client cannot receive from the server. Is it the way server sending is wrong? or the way client receiving is wrong? Do i have to set an IP address for the client?
Any help is appreciated....
You misunderstand the use of Sockets. A socket has both a read channel and a write channel. Both channels are isolated from each other. Looking at your client code, you use use a 'serverSocket' to listen for incoming data while you use a 'clientSocket' to send data to the server. Instead, you should employ the read and write channels of one and the same socket.
As a clarification: a TCP socket is connected. That means that for each socket, a connection is required before the socket can be used. Listening on a socket means that you're expecting to be connected to. In your client, the 'clientSocket' is connecting to the server but the 'serverSocket' is never connected to the server nor is the server ever connecting to the client (which it shouldn't).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.