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");
}
}
}
}
Related
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
//====================Solution found================//
Problem : I have a problem whereby my server program cannot acknowledge another message sent from the client .The first one does though . I'm new to c# , therefore i might have less ideas on how best to achieve this .
Current work : Few things I've done so far were sockets in both server and client program , using backgroundworker and delegates .
So here's the scenario :
client program named KipaSusaMati
server program named Asynchronous Server + Mqtt
Server program were run first , then the client . The client supposedly able to send multiple messages to the port without fail,which the server listened to and take those messages and do something(repetitively).
//-----Server coding----//
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text == "Start Server")
{
listBox1.Items.Add("======================================");
listBox1.Items.Add("Starting server");
changeServerButton(button1);//mok stop
backgroundWorker1.RunWorkerAsync();
}
else
{
listBox1.Items.Add(" Stopping server ....");
changeServerButtonStop(button1);
try
{
if (sListener.Connected)
{
sListener.Shutdown(SocketShutdown.Receive);
sListener.Close();
listBox1.Items.Add(DateTime.Now + " Server Disconnected");
}
else {
listBox1.Items.Add("Socket not in use . Cannot stop socket .");
listBox1.Items.Add(" Press EXIT to exit application. ");
button1.Enabled = false;
button3.Focus();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
permission = new SocketPermission(NetworkAccess.Accept,TransportType.Tcp,"localhost",11000);
sListener = null;
permission.Demand();
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
//IPHostEntry ipHost = Dns.GetHostEntry("localhost");
IPAddress ipAddr = ipHost.AddressList[0];
ipEndPoint = new IPEndPoint(ipAddr, 11000);
sListener = new Socket(ipAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sListener.Bind(ipEndPoint);
sListener.Listen(1);
AsyncCallback aCallback = new AsyncCallback(AcceptCallback);
sListener.BeginAccept(aCallback, sListener);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void AcceptCallback(IAsyncResult ar)
{
Socket listener = null;
Socket handler = null;
try
{
byte[] buffer = new byte[1024];
listener = (Socket)ar.AsyncState;
handler = listener.EndAccept(ar);
handler.NoDelay = false;
object[] obj = new object[2];
obj[0] = buffer;
obj[1] = handler;
handler.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), obj);
AsyncCallback aCallBack = new AsyncCallback(AcceptCallback);
listener.BeginAccept(aCallBack, listener);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ReceiveCallBack(IAsyncResult ar)
{
string stx = "0x02";
string etx = "0x03";
try
{
object[] obj = new object[2];
obj = (object[])ar.AsyncState;
byte[] buffer = (byte[])obj[0];
handler = (Socket)obj[1];
string content = string.Empty;
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
content += Encoding.Unicode.GetString(buffer, 0,
bytesRead);
// If message contains "<Client Quit>", finish receiving
if (content.IndexOf("<Client Quit>") > -1)
{
// Convert byte array to string
string str = content.Substring(0, content.LastIndexOf("<Client Quit>"));
Console.WriteLine("Bytes from client :"+str);
if (content.IndexOf(stx) > -1)
{
Console.WriteLine("STX were detected");
}
else {
Console.WriteLine("STX were not detected");
}
}
else
{
// Continues to asynchronously receive data
byte[] buffernew = new byte[1024];
obj[0] = buffernew;
obj[1] = handler;
handler.BeginReceive(buffernew, 0, buffernew.Length,
SocketFlags.None,
new AsyncCallback(ReceiveCallBack), obj);
}
printMessage(content);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//------Client Coding---------//
private void button1_Click(object sender, EventArgs e)
{
if (button1.Text != "BEGIN")
{
this.Dispose();
listBox1.Items.Add(" Disposing and STOP the application");
}
else
groupboxEnableAll();
listBox1.Items.Add("" + DateTime.Now + " Socket initiated.");
backgroundWorker1.RunWorkerAsync();
button1.Text = "STOP";
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
try
{
SocketPermission permission1 = new SocketPermission(NetworkAccess.Connect, TransportType.Tcp, "localhost", 11000);
permission1.Demand();
senderSock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
senderSock.NoDelay = false;
senderSock.Connect(localEndPoint);
Console.WriteLine("SenderSock rawkkkks!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
listBox1.Items.Add(""+DateTime.Now+" Socket started at port "+port);
}
client-server
From the picture , for the first iteration server managed to get the message sent by client , but for the next iteration , it never displayed .
Solution : Kindly take a look ReceiveCallBack method , instead of doing try catch,im doing do while loop to catch any incoming databytes .
private void ReceiveCallBack(IAsyncResult ar)
{
Console.WriteLine("in ReceiveCallback");
object[] obj = new object[2];
obj = (object[])ar.AsyncState;
byte[] buffer = (byte[])obj[0];
handler = (Socket)obj[1];
string content = string.Empty;
int bytesRead = handler.EndReceive(ar);
do
{
byte[] buffernew = new byte[1024];
obj[0] = buffernew;
obj[1] = handler;
handler.BeginReceive(buffernew, 0, buffernew.Length,
SocketFlags.None,
new AsyncCallback(ReceiveCallBack), obj);
}
while (bytesRead < 0);
content += Encoding.Unicode.GetString(buffer, 0,bytesRead);
printMessage(content);
}
Hope others can benefitting from this .Thanks.
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)
{
}
}
I am trying to make a message server and I have an error with this code:
The error "is only one use of each socket address can be normally permitted"
Server:
class Program
{
//Server Control
static bool stop = false;
static bool pause_listening = false;
//Server Info
static int port = 11000;
static string server_ip = null;
//User Declaration
static List<user> allUsers = new List<user>();
static int users = 0;
//IP Address
static IPAddress ipaddr;
static IPEndPoint localEP;
static IPEndPoint userportEP;
static IPEndPoint temp;
//Data
static string data = null;
static byte[] bytes = new Byte[1024];
//Threads
static Thread listener = new Thread(listen);
static Thread server_control = new Thread(Options);
static Thread UserPort = new Thread(addUserPort);
static void Main(string[] args)
{
Console.WriteLine("Message Server");
start();
}
static void start()
{
server_ip = input("What is your local IPv4 address");
ipaddr = IPAddress.Parse(server_ip);
allUsers.Add(new user());
allUsers[users].name = "Admin";
allUsers[users].ip = server_ip;
allUsers[users].desc = "Nimda";
allUsers[users].id = 0;
localEP = new IPEndPoint(ipaddr, port);
userportEP = new IPEndPoint(ipaddr, 1300);
UserPort.Start();
listener.Start();
server_control.Start();
}
static void addUserPort()
{
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(userportEP);
listener.Listen(10);
Console.WriteLine("User Listener Started");
// Start listening for connections.
while (pause_listening || stop != true)
{
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
string value = null;
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
value += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (value.IndexOf("<!EOM>") > -1)
{
Console.WriteLine("Someone Requested");
if(value.IndexOf( "!au") > -1)
{
String[] rawData = value.Split('|');
String[] userData = new String[3];
for(int x = 0; x < rawData.Length; x++)
{
String stringbuff = rawData[x];
if(stringbuff.IndexOf("name:") > -1)
{
var tempData = stringbuff.Split(':');
userData[x] = tempData[0];
}
else if (stringbuff.IndexOf("ipaddr:") > -1)
{
var tempData = stringbuff.Split(':');
userData[x] = tempData[1];
}
else if (stringbuff.IndexOf("desc:") > -1)
{
var tempData = stringbuff.Split(':');
userData[x] = tempData[2];
}
}
addUser(userData[0], userData[1], userData[2]);
}
break;
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void listen()
{
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
Console.WriteLine("Message Listener Started");
try
{
listener.Bind(localEP);
listener.Listen(10);
while (pause_listening || stop != true)
{
Socket handler = listener.Accept();
data = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<!EOM>") > -1 && data.IndexOf("<!META>") > -1)
{
textSent(data);
break;
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void addUser(String name, String ip, String desc)
{
users++;
allUsers.Add(new user());
userportEP = new IPEndPoint(IPAddress.Parse(ip), 1300);
allUsers[users].name = name;
allUsers[users].ip = ip;
allUsers[users].desc = desc;
allUsers[users].id = users;
byte[] msg = Encoding.ASCII.GetBytes(string.Format("!Join<!PORT>{0}<!PORT><!EOM>", port));
Socket confirm = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
confirm.Bind(userportEP);
confirm.Connect(userportEP);
confirm.Send(msg);
confirm.Shutdown(SocketShutdown.Both);
confirm.Close();
}
static String input(String inputText)
{
Console.WriteLine(inputText);
return Console.ReadLine();
}
static void Options()
{
while(stop == false)
{
Console.Write("\n Server>>");
String command = Console.ReadLine();
switch (command)
{
case "stop":
stop = true;
listener.Abort();
UserPort.Abort();
StopServer();
break;
default:
Console.WriteLine("\t The command \"{0} \" is not valid", command);
break;
}
}
}
static void StopServer()
{
Console.WriteLine("Server is stopping");
Console.Read();
}
static void textSent(String text)
{
String[] rawText = text.Split(new string[] { "<!META>" }, StringSplitOptions.None) ;
String message = rawText[0];
String[] meta = rawText[1].Split(':');
String package = meta[0] + ": " + message + "<!EOM>";
SendToAll(package);
}
static void SendToAll(String pack)
{
byte[] msg = Encoding.ASCII.GetBytes(pack);
Socket send_socket= new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
for (int x = 0; allUsers.Count < x; x++)
{
temp = new IPEndPoint(IPAddress.Parse(allUsers[x].ip), port);
send_socket.Bind(temp);
send_socket.Connect(temp);
send_socket.Send(msg);
}
send_socket.Shutdown(SocketShutdown.Both);
send_socket.Close();
}
}
Client:
class Program
{
static int port;
static string server_ip;
static string ign;
static string desc;
static string ip;
static bool connected = false;
static bool exit = false;
static IPEndPoint remoteEP;
static IPEndPoint remoteUserRequestEP;
static IPEndPoint localEP;
static IPEndPoint userRequestListen;
static Socket listen;
static Socket send;
static Thread listenThread;
static Thread sendThread;
static void Main(string[] args)
{
Console.WriteLine("Message Client");
start();
}
static void start()
{
server_ip = input("Please Enter your Server I.P.");
remoteUserRequestEP = new IPEndPoint(IPAddress.Parse(server_ip), 1300);
ip = input("Enter your local IPv4 Address");
desc = input("Enter a short description");
ign = input("Enter a name to represent yourself");
localEP = new IPEndPoint(IPAddress.Parse(ip), 11000);
userRequestListen = new IPEndPoint(IPAddress.Parse(ip), 1300);
listenThread = new Thread(listening);
sendThread = new Thread(createSend);
listenThread.Start();
sendThread.Start();
}
static String input(String inputText)
{
Console.WriteLine(inputText);
return Console.ReadLine();
}
static void listening()
{
listen = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
String data;
byte[] bytes;
try
{
listen.Bind(localEP);
listen.Listen(1);
while (exit == false)
{
Socket handler = listen.Accept();
data = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<!EOM>") > -1 )
{
string finalMSG = data.Replace("<!EOM>", null);
Console.WriteLine(finalMSG);
break;
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void requestAcesss()
{
byte[] msg = new byte[1024];
msg = Encoding.ASCII.GetBytes(string.Format("!au|name:{0}|ipaddr:{1}|desc:{2}|<!EOM>", ign, ip, desc));
Socket usrRequest = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
usrRequest.Bind(userRequestListen);
usrRequest.Connect(userRequestListen);
usrRequest.Send(msg);
try {
while (connected == false)
{
Socket handler = usrRequest.Accept();
string value = null;
while (true)
{
byte[] bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
value += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (value.IndexOf("<!EOM>") > -1)
{
String[] raw = value.Split(new string[] { "<!PORT>" }, StringSplitOptions.None);
port = Int32.Parse(raw[1]);
remoteEP = new IPEndPoint(IPAddress.Parse(server_ip), port);
localEP = new IPEndPoint(IPAddress.Parse(ip), port);
Console.WriteLine(port);
connected = true;
startServices();
}
break;
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void createSend()
{
byte[] msg = new byte[1024];
send = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
while(exit == false)
{
string raw = Console.ReadLine();
if (raw == "exit")
{
exit = true;
listenThread.Abort();
sendThread.Abort();
stop();
break;
}
string finalmsg = string.Format( raw + "<!META>name:{0}<!META><!EOM>", ign);
send.Bind(localEP);
msg = Encoding.ASCII.GetBytes(finalmsg);
send.Send(msg);
}
send.Shutdown(SocketShutdown.Both);
send.Close();
}
static void startServices()
{
listenThread.Start();
sendThread.Start();
}
static void stop()
{
Console.WriteLine("Press any key to terminate");
Console.ReadLine();
}
}
The sockets aren't used twice nor does a thread get started twice.
Having the same error, I came looking for an answer. Finally found it myself:
An earlier instance of the process may still be running, if you didn't stop it well, e.g. using just Ctrl+C.
I am trying to create asynchronous socket client in multithreaded environment but it is not working correctly.
As below sample code,
If i create new AsyncSocketClient and call StartClent from multi-threaded environment it will process only one or two for rest, it is not processing.(I am creating new AsyncSocketClient with every new request)
Is it because of static variables,
class AsyncSocketClient
{
private static AutoResetEvent sendDone =
new AutoResetEvent(false);
private static AutoResetEvent receiveDone =
new AutoResetEvent(false);
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
static private String response = "";
public void StartClent()
{
Socket workSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// clientSock.ReceiveTimeout = 1;
try
{
workSocket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 8080), new AsyncCallback(ConnectCallBack), workSocket);
connectDone.WaitOne();
Send(s.workSocket, "<EOF>");
sendDone.WaitOne();
Receive(workSocket);
receiveDone.WaitOne();
}
catch(Exception ex)
{
}
}
private void ConnectCallBack(IAsyncResult ar)
{
Socket workSocket = (Socket)ar.AsyncState;
workSocket.EndConnect(ar);
connectDone.Set();
}
private void Receive(Socket client)
{
StateObject state = new StateObject();
state.workSocket = client;
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallBack), state);
}
private void ReceiveCallBack(IAsyncResult ar)
{
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
int byteReceived= client.EndReceive(ar);
if (byteReceived > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, state.buffer.Length));
Array.Clear(state.buffer, 0, state.buffer.Length);
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallBack), state);
}
else
{
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
receiveDone.Set();
}
}
private void Send(Socket client,string data)
{
byte[] sendBufer = Encoding.ASCII.GetBytes(data);
client.BeginSend(sendBufer, 0, sendBufer.Length, 0, new AsyncCallback(BeginSendCallBack), client);
}
private void BeginSendCallBack(IAsyncResult ar)
{
Socket client = (Socket)ar.AsyncState;
int byteSent= client.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", byteSent);
sendDone.Set();
}
}
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 30;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
Here is an example of a non blocking client and server with a simple echo implemented. There is no error checking and nothing is closed correctly which should be done. The server has some synchronous code just to make it easier to follow.
Client
public class AsyncClient
{
private const int Port = 9999;
private readonly string _clientId;
private readonly Random _random;
public AsyncClient(int clientId)
{
_clientId = string.Format("Client Id: {0}", clientId);
_random = new Random(clientId);
}
public void StartClient()
{
try
{
var workSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var state = new ClientState { WorkSocket = workSocket };
workSocket.BeginConnect(new IPEndPoint(IPAddress.Loopback, Port), ConnectCallBack, state);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void ConnectCallBack(IAsyncResult ar)
{
var state = (ClientState) ar.AsyncState;
state.WorkSocket.EndConnect(ar);
Send(state);
}
private void Receive(ClientState clientState)
{
clientState.WorkSocket.BeginReceive(clientState.Buffer, 0, ClientState.BufferSize, 0, ReceiveCallBack, clientState);
}
private void ReceiveCallBack(IAsyncResult ar)
{
var state = (ClientState) ar.AsyncState;
Socket client = state.WorkSocket;
int byteReceived= client.EndReceive(ar);
if (byteReceived > 0)
{
var receivedString = Encoding.UTF8.GetString(state.Buffer, 0, byteReceived);
Console.WriteLine("From Server: " + receivedString);
Array.Clear(state.Buffer, 0, state.Buffer.Length);
state.Count++;
Thread.Sleep(1000 + _random.Next(2000));
Send(state);
}
}
private void Send(ClientState clientState)
{
Console.WriteLine("Sending " + _clientId);
byte[] buffer = Encoding.UTF8.GetBytes(string.Format("Send from Thread {0} Client id {1} Count {2}", Thread.CurrentThread.ManagedThreadId, _clientId,clientState.Count));
clientState.WorkSocket.BeginSend(buffer, 0, buffer.Length, 0, BeginSendCallBack, clientState);
}
private void BeginSendCallBack(IAsyncResult ar)
{
var state = (ClientState) ar.AsyncState;
int byteSent= state.WorkSocket.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", byteSent);
Receive(state);
}
}
public class ClientState
{
// Client socket.
public Socket WorkSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] Buffer = new byte[BufferSize];
public int Count = 0;
}
Server
public class AsyncServer
{
private const int Port = 9999;
public void StartServer()
{
var thread = new Thread(Run) {IsBackground = true};
thread.Start();
}
private void Run()
{
Console.WriteLine("Running");
var tcpListener = new TcpListener(IPAddress.Loopback, Port);
tcpListener.Start();
while (true)
{
Console.WriteLine("Before Accept");
var state = new ServerState {WorkSocket = tcpListener.AcceptSocket()};
Console.WriteLine("Before Recieve");
Receive(state);
}
}
private void Receive(ServerState state)
{
state.WorkSocket.BeginReceive(state.Buffer, 0, ServerState.BufferSize, 0, ReceiveCallBack, state);
}
private void ReceiveCallBack(IAsyncResult ar)
{
Console.WriteLine("ReceiveCallBack");
var state = (ServerState) ar.AsyncState;
try
{
int byteReceived= state.WorkSocket.EndReceive(ar);
if (byteReceived > 0)
{
var receivedString = Encoding.UTF8.GetString(state.Buffer, 0, byteReceived);
Console.WriteLine("Received: " + receivedString);
var bytesToSend = Encoding.UTF8.GetBytes("Server Got --> " + receivedString);
Array.Copy(bytesToSend, state.Buffer, bytesToSend.Length);
state.WorkSocket.Send(state.Buffer, 0, bytesToSend.Length, SocketFlags.None);
Array.Clear(state.Buffer, 0, state.Buffer.Length);
Receive(state);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private class ServerState
{
public const int BufferSize = 1024;
public readonly byte[] Buffer = new byte[1024];
public Socket WorkSocket;
}
I have run this using a console you can either have two applications or just launch the client and server separately.
static void Main(string[] args)
{
if (args.Length != 0)
{
var server = new AsyncServer();
server.StartServer();
}
else
{
for(int i = 0; i < 10; i++)
{
var client = new AsyncClient(i);
client.StartClient();
}
}
Console.WriteLine("Press a key to exit");
Console.ReadKey();
}