C# using Socket to send message to all client - c#

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

Related

(Async. Socket in C#) I do NOT receive the message every time..

I have the following client/ server code in C#, I tested on two computers, they can connect successfully and does not have any problem with the connection
The Problem: when I try sending messages between them, sometimes the message will not be received on the destination computer until them destination send back a message.
Any help is appropriated..
Server:::
public partial class Form1 : Form
{
private byte[] data = new byte[1024];
private int size = 1024;
private Socket server;
private Socket client ;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
stopListining.Enabled = false;
server = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
}
private void startListining_Click(object sender, EventArgs e)
{
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 20916);
server.Bind(iep);
server.Listen(5);
server.BeginAccept(new AsyncCallback(AcceptConn), server);
startListining.Enabled = false;
stopListining.Enabled = true;
}
private void stopListining_Click(object sender, EventArgs e)
{
client.Shutdown(SocketShutdown.Both);
client.Close();
stopListining.Enabled = false;
startListining.Enabled = true;
}
void AcceptConn(IAsyncResult iar)
{
Socket server = (Socket)iar.AsyncState;
client = server.EndAccept(iar);
conStatuss("Connected to: " + client.RemoteEndPoint.ToString());
string stringData = "Server:: Welcome to my server";
byte[] message1 = Encoding.ASCII.GetBytes(stringData);
client.BeginSend(message1, 0, message1.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
}
void SendData(IAsyncResult iar)
{
Socket client = (Socket)iar.AsyncState;
int sent = client.EndSend(iar);
client.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), client);
}
void ReceiveData(IAsyncResult iar)
{
try
{
Socket client = (Socket)iar.AsyncState;
int recv = client.EndReceive(iar);
if (recv == 0)
{
client.Close();
conStatuss("Waiting for client...");
server.BeginAccept(new AsyncCallback(AcceptConn), server);
return;
}
string receivedData = Encoding.ASCII.GetString(data, 0, recv);
addResult(receivedData+"\"R("+DateTime.Now.ToString("h:mm:ss tt")+")\"");
//to send back received text
/*
byte[] message2 = Encoding.ASCII.GetBytes(receivedData);
client.BeginSend(message2, 0, message2.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
*/
}
catch (Exception eee)
{
conStatuss(eee.ToString());
}
}
delegate void SetTextCallback(string text);
private void conStatuss(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.statetxt.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(conStatuss);
this.Invoke(d, new object[] { text });
}
else
{
this.statetxt.Text = text;
}
}
public delegate void AddListBoxItem(string message);
public void addResult(string message)
{
//TODO: find out whats going on here
if (resultss.InvokeRequired)
{
//TODO: Which works better?
//AddListBoxItem albi = AddString;
//listBox.Invoke( albi, message );
resultss.Invoke(new AddListBoxItem(addResult), message);
}
else
this.resultss.Items.Add(message);
}
private void sendButton_Click(object sender, EventArgs e)
{
if (messageTXT.Text.Trim().ToString().Length == 0)
{
conStatuss("Write something to send!");
return;
}
/*
byte[] byData = System.Text.Encoding.ASCII.GetBytes(messageTXT.Text);
client.Send(byData);
resultss.Items.Add("Server:: "+messageTXT.Text);
*/
string stringData = "Server:: " + messageTXT.Text+"\"S("+DateTime.Now.ToString("h:mm:ss tt")+")\"";
addResult(stringData);
byte[] message1 = Encoding.ASCII.GetBytes(stringData);
client.BeginSend(message1, 0, message1.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
messageTXT.Clear();
}
}
Client:::
public partial class Form1 : Form
{
private TextBox newText;
private TextBox conStatus;
private ListBox results;
private Socket client;
private byte[] data = new byte[1024];
private int size = 1024;
public Form1()
{
InitializeComponent();
}
void ButtonConnectOnClick(object obj, EventArgs ea)
{
conStatus.Text = "Connecting...";
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.10.4"), 20916);
newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
}
void ButtonSendOnClick(object obj, EventArgs ea)
{
if (newText.Text.Trim().ToString().Length == 0)
{
conStatuss("Write something to send!");
return;
}
byte[] message = Encoding.ASCII.GetBytes("Client:: " + newText.Text + "\"S(" + DateTime.Now.ToString("h:mm:ss tt") + ")\"");
addResult("Client:: " + newText.Text + "\"S(" + DateTime.Now.ToString("h:mm:ss tt") + ")\"");
//client.Send(message);
client.BeginSend(message, 0, message.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
newText.Clear();
}
void ButtonDisconOnClick(object obj, EventArgs ea)
{
client.Close();
conStatus.Text = "Disconnected";
}
void Connected(IAsyncResult iar)
{
client = (Socket)iar.AsyncState;
try
{
client.EndConnect(iar);
conStatuss("Connected to: " + client.RemoteEndPoint.ToString());
client.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), client);
}
catch (SocketException)
{
conStatuss("Error connecting");
}
}
void ReceiveData(IAsyncResult iar)
{
try
{
Socket remote = (Socket)iar.AsyncState;
int recv = remote.EndReceive(iar);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
addResult(stringData + "\"R(" + DateTime.Now.ToString("h:mm:ss tt") + ")\"");
/*
//to send back received text
byte[] message2 = Encoding.ASCII.GetBytes(stringData);
client.BeginSend(message2, 0, message2.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
*/
}
catch (Exception eee)
{
conStatuss(eee.ToString());
}
}
void SendData(IAsyncResult iar)
{
Socket remote = (Socket)iar.AsyncState;
int sent = remote.EndSend(iar);
remote.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), remote);
}
delegate void SetTextCallback(string text);
private void conStatuss(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.conStatus.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(conStatuss);
this.Invoke(d, new object[] { text });
}
else
{
this.conStatus.Text = text;
}
}
public delegate void AddListBoxItem(string message);
public void addResult(string message)
{
//TODO: find out whats going on here
if (results.InvokeRequired)
{
//TODO: Which works better?
//AddListBoxItem albi = AddString;
//listBox.Invoke( albi, message );
results.Invoke(new AddListBoxItem(addResult), message);
}
else
this.results.Items.Add(message);
}
private void button3_Click(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
}
}

how to get connectionaborted immediately in Asynchronous Programming?

I was doing Asynchronous Programming in c# when I came across this question,when the network is aborted.
My program can get a exception of ConnectionAborted almost 15 seconds after I send a invaild message from client to server.
My question is if I want to get the exception immediately after the network doesn't work,what need I do.
namespace _10_TCP模块化编程
{
class ObjectState
{
public Socket client;
public MyTcp obj;
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
class MyTcp
{
public delegate void dReceiver(object sender, string b);
public event dReceiver receive;
public Socket WebHabor;
//private bool connected;
public MyTcp(IPEndPoint iep, dReceiver dEventCall)
{
//接收消息的委托;
receive += dEventCall;
//创建socket连接;
WebHabor = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ObjectState obs = new ObjectState();
obs.obj = this;
obs.client = WebHabor;
WebHabor.BeginConnect(iep, new AsyncCallback(ConnectCallback), obs);
//connected = WebHabor.Connected ? true : false;
Thread.Sleep(10);
if (WebHabor.Connected == true)
{
Receive();
}
else
{
Program.postLog("连接失败,请检查ip和port");
}
}
public static void ExceptionSolver(SocketException sep)
{
switch (sep.SocketErrorCode)
{
case SocketError.NotConnected:
//捕获ip地址输入错误的情况;
Program.postLog("不存在网络连接");
break;
case SocketError.ConnectionAborted:
//在这里处理频繁出现的错误,
//比如IP不对,网线没插
Program.postLog("连接中止");
break;
case SocketError.ConnectionRefused:
//远程主机正在主动拒绝连接;可能是连接的时候ip或port写错了;
Program.postLog("对方不接受连接,更可能是port的原因");
break;
case SocketError.HostUnreachable:
Program.postLog("连接目标不可达");
break;
case SocketError.TimedOut:
//尝试连接ip超时;
Program.postLog("尝试连接ip超时,更可能是ip的原因");
break;
default:
Program.postLog("捕获到" + sep.SocketErrorCode);
//这里直接报错,如果调试的时候出现这里的错误比较多,就移到上面解决,一般问题都是从来不出的
break;
}
}
public void Send(byte[] dataToSend,int byteCount)
{
try
{
WebHabor.BeginSend(dataToSend, 0, byteCount, 0, new AsyncCallback(SendCallback), WebHabor);
//System.Threading.Thread.Sleep(10);//为了让其它线程跑起来;
}
catch (SocketException sep)
{
Program.postLog("在Send这里");
ExceptionSolver(sep);
}
}
public void Receive()
{
byte[] buffer = new byte[256];
ObjectState obs = new ObjectState();
obs.obj = this;//这个传的是MyTcp;
obs.client = WebHabor;
try
{
WebHabor.BeginReceive(obs.buffer, 0, ObjectState.BufferSize, 0, new AsyncCallback(ReceiveCallback), obs);
}
catch (SocketException sep)
{
Program.postLog("在reveive这里");
ExceptionSolver(sep);
}
//receive.Invoke(this, buffer);
}
//beginConnect的回调函数;
private static void ConnectCallback(IAsyncResult ar)
{
ObjectState obs = (ObjectState)ar.AsyncState;
try
{
// Retrieve the socket from the state object.
Socket client = obs.client;
// Complete the connection.
client.EndConnect(ar);
//Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString());
//连上就连上吧就不发数据了
//MessageBox.Show("Socket connected to " + client.RemoteEndPoint.ToString());
// Signal that the connection has been made.
//connectDone.Set();
}
catch (SocketException sep)
{
//Console.WriteLine(e.ToString());
//MessageBox.Show("connect回调函数出错了" + e.ToString());
/*********************************************************************
*
* 此处需要考察一下连接失败的异常情况。
*
*********************************************************************/
//obs.obj.connected = false;
Program.postLog("在ConnectCallback这里");
ExceptionSolver(sep);
}
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
//System.Threading.Thread.Sleep(10);//为了让其它线程跑起来;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Program.postLog("本次发送" + bytesSent + "个字节");
//Console.WriteLine("Sent {0} bytes to server.", bytesSent);
//MessageBox.Show("Sent " + bytesSent + " bytes to server.");
// Signal that all bytes have been sent.
//sendDone.Set();
}
catch (SocketException sep)
{
//MessageBox.Show("Send回调函数出错了" + e.ToString());
/*********************************************************************
*
* 此处需要考察一下发送失败的异常情况。
*
*********************************************************************/
Program.postLog("在SendCallback这里");
ExceptionSolver(sep);
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
//byte[] buffer = new byte[256];
try
{
// Retrieve the state object and the client socket
// from the asynchronous state object.
//StateObject state = (StateObject)ar.AsyncState;
//Socket client = state.workSocket;
// Read data from the remote device.
ObjectState objs = (ObjectState)ar.AsyncState;
Socket client = objs.client;
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
string getMsg = Encoding.ASCII.GetString(objs.buffer, 0, bytesRead);
//Console.WriteLine("新得到的数据是" + getMsg + "呵呵");
//MessageBox.Show("新得到的数据是" + getMsg);
string msg=Encoding.Default.GetString(objs.buffer, 0, bytesRead);
Program.postLog(msg);
//objs.obj.receive.Invoke(objs.obj, msg);//因为这是静态函数,这个objs.obj实际是MyTcp实例。
//MessageBox.Show(bytesRead.ToString() + "更新数据后:" + state.sb.ToString());
// Get the rest of the data.
client.BeginReceive(objs.buffer, 0, objs.buffer.Length, 0, new AsyncCallback(ReceiveCallback), objs);
}
else
{
//接到0字节说明对方主动断开了连接;
Program.postLog("对方主动断开连接");
}
}
catch (SocketException sep)
{
//MessageBox.Show("Receive回调函数出错了" + e.ToString());
/*********************************************************************
*
* 此处需要考察一下接收失败的异常情况。
*
*********************************************************************/
Program.postLog("在ReceiveCallback这里");
ExceptionSolver(sep);
}
}
}
}
I am not sure, but you can try using TcpClient.Client.Poll method as mentioned in one of the post.

c# SocketAsyncEventArgs blocking code inside ReceiveAsync handler

I have the the following two scenarios that I am testing and one works but the other does not.
I have socket server and socket client application running on two different machines
both the scenarios are using the socketasynceventargs
Scenario 1 (Works)
create 40k socket clients in a loop, wait for all connections to be established and then all clients send messages to the server at the same time and receive response from the server 10 times(i.e. send/receive happens 10 times).
Scenario 2 (Does not work. I get a lot of connection refusal errors)
create 40k socket clients in a loop and send/receive the same 10 messages to the server as soon as each client is connected instead of waiting for the 40k connections to be established.
I cant figure out why my second scenario would fail. i understand that in scenario 1 the server is not doing much until all the 40k connections are made. but it is able to communicate with all the clients at the same time. any ideas??
Thank you for you patience.
here is the socket server code
public class SocketServer
{
private static System.Timers.Timer MonitorTimer = new System.Timers.Timer();
public static SocketServerMonitor socket_monitor = new SocketServerMonitor();
private int m_numConnections;
private int m_receiveBufferSize;
public static BufferManager m_bufferManager;
Socket listenSocket;
public static SocketAsyncEventArgsPool m_readWritePool;
public static int m_numConnectedSockets;
private int cnt = 0;
public static int Closecalled=0;
public SocketServer(int numConnections, int receiveBufferSize)
{
m_numConnectedSockets = 0;
m_numConnections = numConnections;
m_receiveBufferSize = receiveBufferSize;
m_bufferManager = new BufferManager(receiveBufferSize * numConnections ,
receiveBufferSize);
m_readWritePool = new SocketAsyncEventArgsPool(numConnections);
}
public void Init()
{
MonitorTimer.Interval = 30000;
MonitorTimer.Start();
MonitorTimer.Elapsed += new System.Timers.ElapsedEventHandler(socket_monitor.Log);
m_bufferManager.InitBuffer();
SocketAsyncEventArgs readWriteEventArg;
for (int i = 0; i < m_numConnections; i++)
{
readWriteEventArg = new SocketAsyncEventArgs();
m_readWritePool.Push(readWriteEventArg);
}
}
public void Start(IPEndPoint localEndPoint)
{
listenSocket = new Socket(localEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listenSocket.Bind(localEndPoint);
listenSocket.Listen(1000);
StartAccept(null);
}
public void Stop()
{
if (listenSocket == null)
return;
listenSocket.Close();
listenSocket = null;
Thread.Sleep(15000);
}
private void StartAccept(SocketAsyncEventArgs acceptEventArg)
{
if (acceptEventArg == null)
{
acceptEventArg = new SocketAsyncEventArgs();
acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(AcceptEventArg_Completed);
}
else
{
// socket must be cleared since the context object is being reused
acceptEventArg.AcceptSocket = null;
}
try
{
bool willRaiseEvent = listenSocket.AcceptAsync(acceptEventArg);
if (!willRaiseEvent)
{
ProcessAccept(acceptEventArg);
}
}
catch (Exception e)
{
}
}
void AcceptEventArg_Completed(object sender, SocketAsyncEventArgs e)
{
ProcessAccept(e);
}
private void ProcessAccept(SocketAsyncEventArgs e)
{
Interlocked.Increment(ref m_numConnectedSockets);
socket_monitor.IncSocketsConnected();
SocketAsyncEventArgs readEventArgs = m_readWritePool.Pop();
m_bufferManager.SetBuffer(readEventArgs);
readEventArgs.UserToken = new AsyncUserToken { id = cnt++, StarTime = DateTime.Now };
readEventArgs.AcceptSocket = e.AcceptSocket;
SocketHandler handler=new SocketHandler(readEventArgs);
StartAccept(e);
}
}
class SocketHandler
{
private SocketAsyncEventArgs _socketEventArgs;
public SocketHandler(SocketAsyncEventArgs socketAsyncEventArgs)
{
_socketEventArgs = socketAsyncEventArgs;
_socketEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(IO_Completed);
StartReceive(_socketEventArgs);
}
private void StartReceive(SocketAsyncEventArgs receiveSendEventArgs)
{
bool willRaiseEvent = receiveSendEventArgs.AcceptSocket.ReceiveAsync(receiveSendEventArgs);
if (!willRaiseEvent)
{
ProcessReceive(receiveSendEventArgs);
}
}
private void ProcessReceive(SocketAsyncEventArgs e)
{
// check if the remote host closed the connection
AsyncUserToken token = (AsyncUserToken)e.UserToken;
//token.StarTime = DateTime.Now;
if (e.BytesTransferred > 0 && e.SocketError == SocketError.Success)
{
// process the data here
//reply to client
byte[] AckData1 = BitConverter.GetBytes(1);
SendData(AckData1, 0, AckData1.Length, e);
StartReceive(e);
}
else
{
CloseClientSocket(e);
}
}
private void IO_Completed(object sender, SocketAsyncEventArgs e)
{
// determine which type of operation just completed and call the associated handler
switch (e.LastOperation)
{
case SocketAsyncOperation.Receive:
ProcessReceive(e);
break;
case SocketAsyncOperation.Send:
ProcessSend(e);
break;
default:
throw new ArgumentException("The last operation completed on the socket was not a receive or send");
}
}
private void CloseClientSocket(SocketAsyncEventArgs e)
{
AsyncUserToken token = e.UserToken as AsyncUserToken;
// close the socket associated with the client
try
{
e.AcceptSocket.Shutdown(SocketShutdown.Send);
}
catch (Exception ex)
{
}
e.AcceptSocket.Close();
Interlocked.Decrement(ref SocketServer.m_numConnectedSockets);
SocketServer.socket_monitor.DecSocketsConnected();
SocketServer.m_bufferManager.FreeBuffer(e);
e.Completed -= new EventHandler<SocketAsyncEventArgs>(IO_Completed);
SocketServer.m_readWritePool.Push(e);
}
public void SendData(Byte[] data, Int32 offset, Int32 count, SocketAsyncEventArgs args)
{
try
{
Socket socket = args.AcceptSocket;
if (socket.Connected)
{
var i = socket.Send(data, offset, count, SocketFlags.None);
}
}
catch (Exception Ex)
{
}
}
}
here is the client code that throws the error in the connectcallback method
// State object for receiving data from remote device.
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
public int count = 0;
}
public class AsynchronousClient
{
// The port number for the remote device.
private const int port = 11000;
private static int closecalled = 0;
private static bool wait = true;
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
private static ManualResetEvent sendDone =
new ManualResetEvent(false);
private static ManualResetEvent receiveDone =
new ManualResetEvent(false);
// The response from the remote device.
private static String response = String.Empty;
private static void StartClient(Socket client, IPEndPoint remoteEP)
{
// Connect to a remote device.
try
{
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), new StateObject { workSocket = client });
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
StateObject state = (StateObject)ar.AsyncState;
var client = state.workSocket;
// Complete the connection.
client.EndConnect(ar);
var data = "AA5500C08308353816050322462F01020102191552E7D3FA52E7D3FB1FF85BF1FE9F201000004AB80000000500060800001EFFB72F0D00002973620000800000FFFFFFFF00009D6D00003278002EE16D0000018500000000000000000000003A0000000100000000828C80661FF8B436FE9EA9FC000000120000000700000000000000000000000400000000000000000000000000000000000000000000281E0000327800000000000000000000000000AF967D00000AEA000000000000000000000000";
Send(state, data);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Receive(StateObject state)
{
try
{
Socket client = state.workSocket;
// Begin receiving the data from the remote device.
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;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
//if (wait)
//{
// connectDone.WaitOne();
//}
if (bytesRead > 0)
{
state.count = state.count + 1;
byte[] b = new byte[bytesRead];
Array.Copy(state.buffer, b, 1);
if (b[0] == 1)
{
if (state.count < 10)
{
var data = "AA5500C08308353816050322462F01020102191552E7D3FA52E7D3FB1FF85BF1FE9F201000004AB80000000500060800001EFFB72F0D00002973620000800000FFFFFFFF00009D6D00003278002EE16D0000018500000000000000000000003A0000000100000000828C80661FF8B436FE9EA9FC000000120000000700000000000000000000000400000000000000000000000000000000000000000000281E0000327800000000000000000000000000AF967D00000AEA000000000000000000000000";
Send(state, data);
}
else
{
Interlocked.Increment(ref closecalled);
Console.WriteLine("closecalled:-" + closecalled + " at " + DateTime.Now);
client.Close();
}
}
else
{
// Get the rest of the data.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
}
else
{
client.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Send(StateObject state, String data)
{
try
{
Socket client = state.workSocket;
var hexlen = data.Length;
byte[] byteData = new byte[hexlen / 2];
int[] hexarray = new int[hexlen / 2];
int i = 0;
int k = 0;
//create the byte array
while (i < data.Length / 2)
{
string first = data[i].ToString();
i++;
string second = data[i].ToString();
string x = first + second;
byteData[k] = (byte)Convert.ToInt32(x, 16);
i++;
k++;
}
// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Receive(state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
Start();
Console.ReadLine();
return 0;
}
private static void Start()
{
IPAddress ipaddress = IPAddress.Parse("10.20.2.152");
IPEndPoint remoteEP = new IPEndPoint(ipaddress, port);
for (int i = 0; i < 40000; i++)
{
Thread.Sleep(1);
// Create a TCP/IP socket.
try
{
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
StartClient(client, remoteEP);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
if (i == 39999)
{
Console.WriteLine("made all conns at " + DateTime.Now);
}
}
}
}
I would use a linear queue to accept incoming connections. Something like this:
public async Task Accept40KClients()
{
for (int i = 0; i < 40000; i++)
{
// Await this here -------v
bool willRaiseEvent = await listenSocket.AcceptAsync(acceptEventArg);
if (!willRaiseEvent)
{
ProcessAccept(acceptEventArg);
}
}
}
If that's not fast enough, maybe you can do 10 waits at a time, but I think this is good enough... I might be wrong on this though.

console window starts behind gui

I have created a gui for server but whenever I start gui a console window also opens and if I close console window the gui also closes. The console window doesn't do anything it just opens when I start my gui. How can I avoid this? I want only gui to start and not console window.
namespace ServerUI
{
public partial class Server : Form
{
public Server()
{
InitializeComponent();
//default port number
textBox1.Text = "8001";
button1.Click += button1_Click;
}
//Global Variables
public static class Globals
{
public const string IP = "127.0.0.1";
public static int port_number = 0;
public static string selected = "";
public static string selected_1 = "";
}
//IP address of server
static IPAddress ipAddress = IPAddress.Parse(Globals.IP);
//List of active clients connected to server
List<Socket> active_clients = new List<Socket>();
static Socket serverSocket;
static byte[] buffer = new Byte[1024];
public static ManualResetEvent allDone = new ManualResetEvent(false);
private void button1_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(textBox1.Text.Trim()))
{
System.Windows.Forms.MessageBox.Show("Port Number Empty", "Error");
return;
}
else
{
bool check = int.TryParse(textBox1.Text, out Globals.port_number);
if (!check)
{
MessageBox.Show("Port Number not in correct format. Enter Port Number again", "Error");
return;
}
client_pkt_parsing.client_list.Clear();
foreach (DataGridViewRow myRow in dataGridView1.Rows)
{
myRow.Cells[1].Value = null; // assuming you want to clear the first column
}
foreach (DataGridViewRow myRow in dataGridView2.Rows)
{
myRow.Cells[1].Value = null; // assuming you want to clear the first column
}
//Starting Server
StartServer();
}
} //end of button1_Click
public void StartServer()
{
byte[] bytes = new Byte[1024];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, Globals.port_number);
try
{
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(localEndPoint);
serverSocket.Listen(10);
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
infoBox.Text = "Server started. Waiting for a connection...";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}//end of StartServer
public void AcceptCallback(IAsyncResult ar)
{
allDone.Set();
try
{
Socket clientSocket = serverSocket.EndAccept(ar);
infoBox.Text = infoBox.Text + "\r\n" + string.Format(DateTime.Now.ToString("HH:mm:ss") + " > Client : " + clientSocket.RemoteEndPoint.ToString() + "connected");
clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), clientSocket);
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
catch (Exception ex)
{
}
}//end of AcceptCallback
public void ReceiveCallback(IAsyncResult ar)
{
try
{
int received = 0;
Socket current = (Socket)ar.AsyncState;
received = current.EndReceive(ar);
byte[] data = new byte[received];
if (received == 0)
{
return;
}
Array.Copy(buffer, data, received);
string text = Encoding.ASCII.GetString(data);
testBox.Text = testBox.Text + "\r\n" + text;
//Send(current, "hello");
buffer = null;
Array.Resize(ref buffer, current.ReceiveBufferSize);
current.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), current);
}
catch (Exception ex)
{
}
}//end of RecieveCallback
}
}
This typically happens when you started with the wrong project template. It is fixable. Use Project + Properties, Application tab. Change the "Output type" setting from Console Application to Windows Application. No more console.

Server Client send/receive simple text

I have a homework to build an application which will send and receive simple string between server and client. I know how to establish connection, but don't know how to send and receive string. This is my code :
public partial class Form1 : Form
{
private Thread n_server;
private Thread n_client;
private Thread n_send_server;
private TcpClient client;
private TcpListener listener;
private int port = 2222;
private string IP = " ";
private Socket socket;
public Form1()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
public void Server()
{
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
try
{
socket = listener.AcceptSocket();
if (socket.Connected)
{
textBox2.Invoke((MethodInvoker)delegate { textBox2.Text = "Client : " + socket.RemoteEndPoint.ToString(); });
}
}
catch
{
}
}
public void Client()
{
IP = "localhost";
client = new TcpClient();
try
{
client.Connect(IP, port);
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
if (client.Connected)
{
textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Connected..."; });
}
}
private void button1_Click(object sender, EventArgs e)
{
n_server = new Thread(new ThreadStart(Server));
n_server.IsBackground = true;
n_server.Start();
textBox1.Text = "Server up";
}
private void button2_Click(object sender, EventArgs e)
{
n_client = new Thread(new ThreadStart(Client));
n_client.IsBackground = true;
n_client.Start();
}
private void send()
{
// I want to use this method for both buttons : "send button" on server side and "send button"
// on client side. First I read text from textbox2 on server side or textbox3
// on client side than accept and write the string to label2(s) or label3(c).
//
}
private void button3_Click(object sender, EventArgs e)
{
n_send_server = new Thread(new ThreadStart(send));
n_send_server.IsBackground = true;
n_send_server.Start();
}
}
The following code send and recieve the current date and time from and to the server
//The following code is for the server application:
namespace Server
{
class Program
{
const int PORT_NO = 5000;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
//---listen at the specified IP and port no.---
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received : " + dataReceived);
//---write back the text to the client---
Console.WriteLine("Sending back : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
client.Close();
listener.Stop();
Console.ReadLine();
}
}
}
//this is the code for the client
namespace Client
{
class Program
{
const int PORT_NO = 5000;
const string SERVER_IP = "127.0.0.1";
static void Main(string[] args)
{
//---data to send to the server---
string textToSend = DateTime.Now.ToString();
//---create a TCPClient object at the IP and port no.---
TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);
//---send the text---
Console.WriteLine("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
//---read back the text---
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
Console.ReadLine();
client.Close();
}
}
}
static void Main(string[] args)
{
//---listen at the specified IP and port no.---
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();
while (true)
{
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received : " + dataReceived);
//---write back the text to the client---
Console.WriteLine("Sending back : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
client.Close();
}
listener.Stop();
Console.ReadLine();
}
In addition to #Nudier Mena answer, keep a while loop to keep the server in listening mode. So that we can have multiple instance of client connected.
public partial class Form1 : Form
{
private Thread n_server;
private Thread n_client;
private Thread n_send_server;
private TcpClient client;
private TcpListener listener;
private int port = 2222;
private string IP = " ";
private Socket socket;
byte[] bufferReceive = new byte[4096];
byte[] bufferSend = new byte[4096];
public Form1()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
public void Server()
{
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
try
{
socket = listener.AcceptSocket();
if (socket.Connected)
{
textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Client : " + socket.RemoteEndPoint.ToString(); });
}
while (true)
{
int length = socket.Receive(bufferReceive);
if (length > 0)
{
label2.Invoke((MethodInvoker)delegate { label2.Text = Encoding.Unicode.GetString(bufferReceive); });
}
}
}
catch
{
}
}
public void Client()
{
IP = "localhost";
client = new TcpClient();
try
{
client.Connect(IP, port);
while (true)
{
NetworkStream nts = client.GetStream();
int length;
while ((length = nts.Read(bufferReceive, 0, bufferReceive.Length)) != 0)
{
label3.Invoke((MethodInvoker)delegate { label3.Text = Encoding.Unicode.GetString(bufferReceive); });
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}
if (client.Connected)
{
textBox3.Invoke((MethodInvoker)delegate { textBox3.Text = "Connected..."; });
}
}
private void button1_Click(object sender, EventArgs e)
{
n_server = new Thread(new ThreadStart(Server));
n_server.IsBackground = true;
n_server.Start();
textBox1.Text = "Server up";
}
private void button2_Click(object sender, EventArgs e)
{
n_client = new Thread(new ThreadStart(Client));
n_client.IsBackground = true;
n_client.Start();
}
private void send()
{
if (socket!=null)
{
bufferSend = Encoding.Unicode.GetBytes(textBox2.Text);
socket.Send(bufferSend);
}
else
{
if (client.Connected)
{
bufferSend = Encoding.Unicode.GetBytes(textBox3.Text);
NetworkStream nts = client.GetStream();
if (nts.CanWrite)
{
nts.Write(bufferSend,0,bufferSend.Length);
}
}
}
}
private void button3_Click(object sender, EventArgs e)
{
n_send_server = new Thread(new ThreadStart(send));
n_send_server.IsBackground = true;
n_send_server.Start();
}
}
bool SendReceiveTCP(string ipAddress, string sendMsg, ref string recMsg)
{
try
{
DateTime startTime=new DateTime();
TcpClient clt = new TcpClient();
clt.Connect(ipAddress, 8001);
NetworkStream nts = clt.GetStream();
nts.Write(Encoding.ASCII.GetBytes(sendMsg),0, sendMsg.Length);
startTime = DateTime.Now;
while (true)
{
if (nts.DataAvailable)
{
byte[] tmpBuff = new byte[1024];
System.Threading.Thread.Sleep(100);
int readOut=nts.Read(tmpBuff, 0, 1024);
if (readOut > 0)
{
recMsg = Encoding.ASCII.GetString(tmpBuff, 0, readOut);
nts.Close();
clt.Close();
return true;
}
else
{
nts.Close();
clt.Close();
return false;
}
}
TimeSpan tps = DateTime.Now - startTime;
if (tps.TotalMilliseconds > 2000)
{
nts.Close();
clt.Close();
return false;
}
System.Threading.Thread.Sleep(50);
}
}
catch (Exception ex)
{
throw ex;
}
}
CLIENT
namespace SocketKlient
{
class Program
{
static Socket Klient;
static IPEndPoint endPoint;
static void Main(string[] args)
{
Klient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
string command;
Console.WriteLine("Write IP address");
command = Console.ReadLine();
IPAddress Address;
while(!IPAddress.TryParse(command, out Address))
{
Console.WriteLine("wrong IP format");
command = Console.ReadLine();
}
Console.WriteLine("Write port");
command = Console.ReadLine();
int port;
while (!int.TryParse(command, out port) && port > 0)
{
Console.WriteLine("Wrong port number");
command = Console.ReadLine();
}
endPoint = new IPEndPoint(Address, port);
ConnectC(Address, port);
while(Klient.Connected)
{
Console.ReadLine();
Odesli();
}
}
public static void ConnectC(IPAddress ip, int port)
{
IPEndPoint endPoint = new IPEndPoint(ip, port);
Console.WriteLine("Connecting...");
try
{
Klient.Connect(endPoint);
Console.WriteLine("Connected!");
}
catch
{
Console.WriteLine("Connection fail!");
return;
}
Task t = new Task(WaitForMessages);
t.Start();
}
public static void SendM()
{
string message = "Actualy date is " + DateTime.Now;
byte[] buffer = Encoding.UTF8.GetBytes(message);
Console.WriteLine("Sending: " + message);
Klient.Send(buffer);
}
public static void WaitForMessages()
{
try
{
while (true)
{
byte[] buffer = new byte[64];
Console.WriteLine("Waiting for answer");
Klient.Receive(buffer, 0, buffer.Length, 0);
string message = Encoding.UTF8.GetString(buffer);
Console.WriteLine("Answer: " + message);
}
}
catch
{
Console.WriteLine("Disconnected");
}
}
}
}
Server:
namespace SocketServer
{
class Program
{
static Socket klient;
static void Main(string[] args)
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 8888);
server.Bind(endPoint);
server.Listen(20);
while(true)
{
Console.WriteLine("Waiting...");
klient = server.Accept();
Console.WriteLine("Client connected");
Task t = new Task(ServisClient);
t.Start();
}
}
static void ServisClient()
{
try
{
while (true)
{
byte[] buffer = new byte[64];
Console.WriteLine("Waiting for answer...");
klient.Receive(buffer, 0, buffer.Length, 0);
string message = Encoding.UTF8.GetString(buffer);
Console.WriteLine("Answer: " + message);
string answer = "Actualy date is " + DateTime.Now;
buffer = Encoding.UTF8.GetBytes(answer);
Console.WriteLine("Sending {0}", answer);
klient.Send(buffer);
}
}
catch
{
Console.WriteLine("Disconnected");
}
}
}
}

Categories

Resources