How do I keep accepting data on my async socket? - c#

So I've setup a very basic server and a client, utilizing the Socket class in C#.
I did one earlier where it wasnt async so I decided to try it out.
The issue I am having is that I keep sending data from the server to the client, but the client only gets the first one and then it's as if it stops listening.
What ways are there to keep checking if there is incoming data and then if there is just grab it?
Client
private static Socket _clientSocket;
private static byte[] buffer = new byte[2048];
static void Main(string[] args)
{
Connect();
Console.ReadLine();
}
private static void Connect()
{
try
{
_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_clientSocket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 1234), new AsyncCallback(ConnectCallback), null);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
private static void ConnectCallback(IAsyncResult AR)
{
try
{
_clientSocket.EndConnect(AR);
Console.WriteLine("Connected to the server");
_clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None,
new AsyncCallback(ReceiveCallback), _clientSocket);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
private static void ReceiveCallback(IAsyncResult AR)
{
Socket clientSocket = AR.AsyncState as Socket;
var length = clientSocket.EndReceive(AR);
byte[] packet = new byte[length];
Array.Copy(buffer, packet, packet.Length);
var data = Encoding.ASCII.GetString(packet);
Console.WriteLine("Received " + data);
}
And the server
private static Socket _clientSocket;
private static byte[] buffer = new byte[2048];
static void Main(string[] args)
{
Connect();
Console.ReadLine();
}
private static void Connect()
{
try
{
_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_clientSocket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 1234), new AsyncCallback(ConnectCallback), null);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
private static void ConnectCallback(IAsyncResult AR)
{
try
{
_clientSocket.EndConnect(AR);
Console.WriteLine("Connected to the server");
_clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None,
new AsyncCallback(ReceiveCallback), _clientSocket);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
private static void ReceiveCallback(IAsyncResult AR)
{
Socket clientSocket = AR.AsyncState as Socket;
var length = clientSocket.EndReceive(AR);
byte[] packet = new byte[length];
Array.Copy(buffer, packet, packet.Length);
var data = Encoding.ASCII.GetString(packet);
Console.WriteLine("Received " + data);
}

In your ReceiveCallback, call BeginReceive again to continue receiving.

Related

how to connect to my local server from external network computer or within the same network using c# socket

I have set-up a server running on my local host that uses sockets. Also I have created a client application that connects to the server using socket. I have successfully connected to the server from the same computer but what I am trying to do is that to connect to the server from different computer from within the network. What I did is that I ran the server on the local host and on the client side I provided the local IP address of the computer that runs on the server and I set up the port on 90 so the server listen for connection in this port. The problem is that I can't connect to the server and the application keeps trying to connect and attempts with no result. How can I fix this. Also a point to mention is that I have disabled firewall and antivirus to allow for connection but still I get no result. can someone help.
Code for server :
class Program
{
private static IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
private static Socket _serverSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
private static List<Socket> _clientSockerts = new List<Socket>();
private static byte[] _buffer = new byte[1024];
static void Main(string[] args)
{
SetupServer();
Console.ReadLine();
}
private static void SetupServer()
{
Console.WriteLine("Setting UP Server");
_serverSocket.Bind(new IPEndPoint(ipAddress, 90));
_serverSocket.Listen(1);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallBack), null);
}
private static void AcceptCallBack(IAsyncResult AR)
{
Socket socket = _serverSocket.EndAccept(AR);
_clientSockerts.Add(socket);
Console.WriteLine("Client Connects");
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallBack), null);
}
private static void ReceiveCallBack(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
int recived = socket.EndReceive(AR);
byte[] dataBuf = new byte[recived];
Array.Copy(_buffer, dataBuf, recived);
string text = Encoding.ASCII.GetString(dataBuf);
Console.WriteLine("text recived: " + text);
string response = string.Empty;
if (text.ToLower() != "get time")
{
response = "Invaild Request";
}
else
{
response = DateTime.Now.ToLongTimeString();
}
byte[] data = Encoding.ASCII.GetBytes(text);
socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(sendCallBack), socket);
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
}
private static void sendCallBack(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
socket.EndSend(AR);
}
}
Code for client:
class Program
{
private static IPAddress ipAddress = Dns.GetHostEntry("192.168.1.3").AddressList[0];
private static Socket _clientSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
static void Main(string[] args)
{
LoopConnect();
sendLoop();
Console.ReadLine();
}
private static void sendLoop()
{
while(true)
{
Thread.Sleep(500);
Console.WriteLine("Enter a request: ");
string req = Console.ReadLine();
byte[] buffer = Encoding.ASCII.GetBytes(req);
_clientSocket.Send(buffer);
byte[] reciveBuf = new byte[1024];
int rec = _clientSocket.Receive(reciveBuf);
byte[] data = new byte[rec];
Array.Copy(reciveBuf,data,rec);
Console.WriteLine("Recived: " + Encoding.ASCII.GetString(data));
}
}
private static void LoopConnect()
{
int attempts = 0;
while (!_clientSocket.Connected)
{
try
{
attempts++;
_clientSocket.Connect("192.168.1.3", 90);
}
catch (SocketException)
{
Console.Clear();
Console.WriteLine("Connection attempts: " + attempts.ToString());
}
}
Console.Clear();
Console.WriteLine("Connected");
}
}

System.Net.Sockets.SocketException: 'An existing connection was forcibly closed by the remote host'

I create a TCP connection between a server and a client, but after few requests I have this error message :
System.Net.Sockets.SocketException: 'An existing connection was forcibly closed by the remote host'
On this line :
_clientSocket.Send(buffer,0,buffer.Length,SocketFlags.None);
How can I resolve this error ?
Server code
private static Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private static List<Socket> _clientSockets = new List<Socket>();
private static byte[] _buffer = new byte[1024];
protected override void OnStart(string[] args)
{
SetupServer();
}
private static void SetupServer()
{
Log.writeEventLog("Setting up server...");
_serverSocket.Bind(new IPEndPoint(IPAddress.Any, 100));
_serverSocket.Listen(1);// max listen client
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
private static void AcceptCallback(IAsyncResult AR)
{
Socket socket = _serverSocket.EndAccept(AR);
_clientSockets.Add(socket);
Log.writeEventLog("Client connected");
socket.BeginReceive(_buffer,0,_buffer.Length,SocketFlags.None,new AsyncCallback(ReceiveCallback),socket);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
private static void ReceiveCallback(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
int received = socket.EndReceive(AR);
byte[] dataBuf = new byte[received];
Array.Copy(_buffer,dataBuf,received);
string text = Encoding.ASCII.GetString(dataBuf);
Log.writeEventLog("TEXT RECEIVED: " + text);
string response = string.Empty;
if(text.ToLower() != "get authentication key")
{
response = "Invalid Request";
}
else
{
response = "TEST";
}
byte[] data = Encoding.ASCII.GetBytes(response);
socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallBack), null);
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
}
private static void SendCallBack(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
socket.EndSend(AR);
}
Client code
private static Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
static void Main(string[] args)
{
LoopConnect();
SendLoop();
Console.ReadLine();
Console.ReadKey();
}
private static void SendLoop()
{
while (true)
{
Console.WriteLine("Enter a request: ");
string req = Console.ReadLine();
byte[] buffer = Encoding.ASCII.GetBytes(req);
_clientSocket.Send(buffer,0,buffer.Length,SocketFlags.None);
var receivedBuffer = new byte[2048];
int rec = _clientSocket.Receive(receivedBuffer,SocketFlags.None);
byte[] data = new byte[rec];
Array.Copy(receivedBuffer, data, rec);
Console.WriteLine("Received : " + Encoding.ASCII.GetString(data));
}
}
private static void LoopConnect()
{
int attempts = 0;
while (!_clientSocket.Connected)
{
try
{
attempts++;
_clientSocket.Connect(IPAddress.Loopback, 100);
}
catch (SocketException) {
Console.Clear();
Console.WriteLine("Connection attenpts: "+ attempts.ToString());
}
}
Console.Clear();
Console.WriteLine("Connected");
}
Update:
socket.BeginSend(data, 0, data.Length, SocketFlags.None,
new AsyncCallback(SendCallBack), socket);

C# using Socket to send message to all client

My objective here to to send a message to the connected clients from my server. The code is working but the only problem is, it can only send message to the client who sent the command. What I need is to received the message by other client. I saw this code in youtube and make a few adjustment. Please find below.
Server Code
class Program
{
private static readonly Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private static readonly List<Socket> clientSockets = new List<Socket>();
private const int BUFFER_SIZE = 2048;
private const int PORT = 100;
private static readonly byte[] buffer = new byte[BUFFER_SIZE];
static void Main(string[] args)
{
Console.Title = "Server";
SetupServer();
Console.ReadLine(); // When we press enter close everything
CloseAllSockets();
}
private static void SetupServer()
{
Console.WriteLine("Setting up server...");
serverSocket.Bind(new IPEndPoint(IPAddress.Any, PORT));
serverSocket.Listen(0);
serverSocket.BeginAccept(AcceptCallback, null);
Console.WriteLine("Server setup complete");
}
/// <summary>
/// Close all connected client (we do not need to shutdown the server socket as its connections
/// are already closed with the clients).
/// </summary>
private static void CloseAllSockets()
{
foreach (Socket socket in clientSockets)
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
serverSocket.Close();
}
private static void AcceptCallback(IAsyncResult AR)
{
Socket socket;
try
{
socket = serverSocket.EndAccept(AR);
}
catch (ObjectDisposedException) // I can not seem to avoid this (on exit when properly closing sockets)
{
return;
}
clientSockets.Add(socket);
socket.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, socket);
Console.WriteLine("{0}", socket.RemoteEndPoint + " connected...");
serverSocket.BeginAccept(AcceptCallback, null);
}
private static void ReceiveCallback(IAsyncResult AR)
{
Socket current = (Socket)AR.AsyncState;
int received;
try
{
received = current.EndReceive(AR);
}
catch (SocketException)
{
Console.WriteLine("Client forcefully disconnected");
// Don't shutdown because the socket may be disposed and its disconnected anyway.
current.Close();
clientSockets.Remove(current);
return;
}
byte[] recBuf = new byte[received];
Array.Copy(buffer, recBuf, received);
string text = Encoding.ASCII.GetString(recBuf);
Console.WriteLine("Received Text: " + text);
if (text.ToLower() == "meeting") // Client requested time
{
foreach (Socket socket in clientSockets)
{
//current = socket;
string message = "meeting";
byte[] data = Encoding.ASCII.GetBytes(message);
socket.Send(data);
//socket.BeginSend(data, 0, data.Length, SocketFlags.None, null, null);
Console.WriteLine("Meeting invite sent to " + socket.RemoteEndPoint);
}
}
else if (text.ToLower() == "exit") // Client wants to exit gracefully
{
// Always Shutdown before closing
Console.WriteLine(current.RemoteEndPoint + " disconnected");
current.Shutdown(SocketShutdown.Both);
current.Close();
clientSockets.Remove(current);
return;
}
else
{
Console.WriteLine("Invalid request");
byte[] data = Encoding.ASCII.GetBytes("Invalid request");
current.Send(data);
Console.WriteLine("Warning Sent");
}
current.BeginReceive(buffer, 0, BUFFER_SIZE, SocketFlags.None, ReceiveCallback, current);
}
}
Client Code
namespace TCP_Client {
public partial class frmTCPClient : Form
{
private readonly Socket ClientSocket = new Socket
(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private const int PORT = 100;
private byte[] buffer;
private string message { get; set; }
public string serverMessage { get; set; }
public frmTCPClient()
{
InitializeComponent();
}
private void frmTCPClient_Load(object sender, EventArgs e)
{
ConnectToServer();
//UpdateControls();
}
private void UpdateControls()
{
lblMessage.Text = message;
//txtFromServer.Text = serverMessage;
}
private void ConnectToServer()
{
int attempts = 0;
while (!ClientSocket.Connected)
{
try
{
attempts++;
//lblMessage.Text = "Connection attempt " + attempts;
// Change IPAddress.Loopback to a remote IP to connect to a remote host.
//ClientSocket.Connect(IPAddress.Loopback, PORT);
ClientSocket.Connect("172.20.110.129", PORT);
}
catch (SocketException ex)
{
MessageBox.Show(ex.Message + Environment.NewLine + "Connection attempt " + attempts);
}
}
message = "Connected";
}
private void RequestLoop()
{
while (true)
{
SendRequest("");
ReceiveResponse();
}
}
private void SendRequest(string text)
{
string request = text;
SendString(request);
if (request.ToLower() == "exit")
{
Exit();
}
}
/// <summary>
/// Sends a string to the server with ASCII encoding.
/// </summary>
private void SendString(string text)
{
try
{
byte[] buffer = Encoding.ASCII.GetBytes(text);
ClientSocket.Send(buffer, 0, buffer.Length, SocketFlags.None);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
SendRequest(txtMessage.Text);
ReceiveResponse();
UpdateControls();
}
private void Exit()
{
SendString("exit"); // Tell the server we are exiting
ClientSocket.Shutdown(SocketShutdown.Both);
ClientSocket.Close();
Environment.Exit(0);
}
public void ReceiveResponse()
{
var buffer = new byte[2048];
try
{
if (buffer.ToString().Length == 2048) return;
int received = ClientSocket.Receive(buffer, SocketFlags.None);
if (received == 0) return;
var data = new byte[received];
Array.Copy(buffer, data, received);
string text = Encoding.ASCII.GetString(data);
txtFromServer.Text += text + System.Environment.NewLine;
//MessageBox.Show(text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
}
private void frmTCPClient_FormClosed(object sender, FormClosedEventArgs e)
{
Exit();
}
} }
Update
foreach (object obj in clientSockets)
{
string message = "meeting";
byte[] data = Encoding.ASCII.GetBytes(message);
Socket socket = (Socket)obj;
socket.Send(data);
Console.WriteLine("Meeting invite sent to " + socket.RemoteEndPoint);
}
Image
enter image description here

C# Asynchronous Chat Server

I'm trying to build an Asynchronous Chat Server and this is what I got so far:
Server
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 1024;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousSocketListener
{
public static ManualResetEvent allDone = new ManualResetEvent(false);
public AsynchronousSocketListener()
{
}
public static void StartListening()
{
byte[] bytes = new Byte[1024];
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
Socket listener = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
allDone.Reset();
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
allDone.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1)
{
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",content.Length, content);
Send(handler, content);
}
else
{
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReadCallback), state);
}
}
}
private static void Send(Socket handler, String data)
{
byte[] byteData = Encoding.ASCII.GetBytes(data);
handler.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState;
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}
Client
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
public class StateObject
{
public Socket workSocket = null;
public const int BufferSize = 256;
public byte[] buffer = new byte[BufferSize];
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousClient
{
private const int port = 11000;
private static ManualResetEvent connectDone =new ManualResetEvent(false);
private static ManualResetEvent sendDone =new ManualResetEvent(false);
private static ManualResetEvent receiveDone =new ManualResetEvent(false);
private static String response = String.Empty;
static String username = "";
static int a = 1;
private static void StartClient()
{
try
{
Console.WriteLine("Username: ");
username = Console.ReadLine();
while (a == 1)
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
Console.WriteLine("Receiver: ");
String receiver = Console.ReadLine();
Console.WriteLine("Message: ");
String message = Console.ReadLine();
String Message = username + "[" + receiver + "[" + message + "<EOF>";
Send(client, Message);
sendDone.WaitOne();
Receive(client);
receiveDone.WaitOne();
Console.WriteLine("Response received : {0}", response);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
client.EndConnect(ar);
connectDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Receive(Socket client)
{
try
{
StateObject state = new StateObject();
state.workSocket = client;
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,new AsyncCallback(ReceiveCallback), state);
}
else
{
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
receiveDone.Set();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Send(Socket client, String data)
{
byte[] byteData = Encoding.ASCII.GetBytes(data);
client.BeginSend(byteData, 0, byteData.Length, 0,new AsyncCallback(SendCallback), client);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
Socket client = (Socket)ar.AsyncState;
int bytesSent = client.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", bytesSent);
sendDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
StartClient();
return 0;
}
}
I'm able to send messages to the server and get back an answer, but the connection is cut every time and I have to reconnect it and like this I wouldn't be able to get messages after I send one. I'm looking for a way to connect my client to the server, send messages in both ways and stop the connection manualy.
Furthermore I'm looking for a way to send messages from one client to another one and to send a message to all clients, who are connected to the server.
Another Question I have, how can I set up multiple ports and let the server listen to all ports? I wanted to open one port for the login and one port for the messages.
I'm looking for a way to connect my client to the server, send messages in both ways and stop the connection manualy.
Closing the connection could be done by adding a disconnect call after the loop: client.Disconnect(false). After some exit condition you simply quit the loop.
It would be preferable to create the client in a using statement though, this way it will be disposed automatically.
but the connection is cut every time
because your explicitly close it in SendCallback
Socket handler = (Socket) ar.AsyncState;
handler.Shutdown(SocketShutdown.Both);
handler.Close();
You may call handler.BeginReceive instead

Send byte[] continuously from server to client?

I'm pretty new to this, I just want to send a message from my console server window to the client.
Here's my server:
static void Main(string[] args)
{
try
{
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 8000);
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
newsock.Bind(localEndPoint);
newsock.Listen(10);
Socket client = newsock.Accept();
if (client.Connected)
{
Console.WriteLine("client connected.");
}
string msg = "Who's there?";
byte[] buffer = new byte[msg.Count()];
buffer = Encoding.ASCII.GetBytes(msg);
client.Send(buffer);
It works fine when i use client.Send() above, but when when I do as follows below I receive nothing on the other end. Since the client is connected, I see no reason why it fails.
while (client.Connected)
{
Console.WriteLine("enter msg: ");
string userMsg = Console.ReadLine();
byte[] userBuffer = new byte[userMsg.Count()];
userBuffer = Encoding.ASCII.GetBytes(userMsg);
client.Send(userBuffer);
Console.ReadKey();
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e);
}
}
Here's the code for the client:
public partial class MainWindow : Window
{
Socket server = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000);
byte[] buffer = new byte[12];
public MainWindow()
{
InitializeComponent();
}
private void btn_Connect_Click(object sender, RoutedEventArgs e)
{
server = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
server.Connect(ipep);
if (server.Connected)
{
txt_Log.AppendText("\nConnected to target server.");
}
btn.IsEnabled = false;
btn_disc.IsEnabled = true;
}
private void btn_Disconnect_Click(object sender, RoutedEventArgs e)
{
server.Close();
if (!server.Connected)
{
txt_Log.AppendText("\nDisconnected to target server.");
}
btn.IsEnabled = true;
btn_disc.IsEnabled = false;
}
private void btn_Fetch_Click(object sender, RoutedEventArgs e)
{
if (buffer != null)
{
using (server)
{
server.Receive(buffer);
txt_Log.AppendText(System.Text.Encoding.Default.GetString(buffer));
buffer = null;
}
}
else
{
txt_Log.AppendText("\nNo data to send.");
}
}
}
Well I've run your server code. No problems there...
For the client, it seemed you dispose the server, which drops the connnection? and null the buffer, so you can't re-use that either....
I wrote some test client code which seemed to work fine
class Program
{
static void Main(string[] args)
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Connect("127.0.0.1", 8000);
byte[] buffer = new byte[1024];
while (true)
{
int bytes = server.Receive(buffer);
Console.WriteLine(System.Text.Encoding.Default.GetString(buffer, 0, bytes));
}
}
}
Note that the point of this you don't disconnect the client every time you read a packet, and if you null your static before and then null check it is going to be null so fetch will only work once, therefore don't do it!
Also as Mark said, check the number of bytes read from the call the Receive so you can tell how many bytes to decode.
Change
private void btn_Fetch_Click(object sender, RoutedEventArgs e)
{
if (buffer != null)
{
using (server)
{
server.Receive(buffer);
txt_Log.AppendText(System.Text.Encoding.Default.GetString(buffer));
buffer = null;
}
}
else
{
txt_Log.AppendText("\nNo data to send.");
}
}
To..
private void btn_Fetch_Click(object sender, RoutedEventArgs e)
{
if (buffer != null)
{
server.Receive(buffer);
txt_Log.AppendText(System.Text.Encoding.Default.GetString(buffer));
buffer = null;
}
else
{
txt_Log.AppendText("\nNo data to send.");
}
}
and call dispose when the window is closed
protected override void OnClosed(EventArgs e) {
base.OnClosed(e);
server.Dispose();
}

Categories

Resources