Broadcasting message over UDP C# - c#

I'm having communication problems with my Program.cs class and my handleClinet.cs class.. Program handles accepting connection from every new client that attempts connecting, and handleClinet is responsible for handling every client's individual interaction.
I have a while loop in each class which is, i assume, where the problem lies.. but I'm not sure how else to do this. The server responses are not corresponding to what they're supposed to be responding. (i.e. not going into my broadcast function and executing the statements in the Program while loop) does anyone have a solution to this? Thanks in advance
class Program
{
public static Hashtable clientsList = new Hashtable();
static void Main(string[] args)
{
UdpClient server = new UdpClient(8888);
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
string data = "";
Console.WriteLine("Auction Server Started ....");
while (true)
{
try
{
//Reads data
byte[] inStream = server.Receive(ref remoteEndPoint);
data = Encoding.ASCII.GetString(inStream);
Console.WriteLine("REGISTER Client at " + remoteEndPoint);
byte[] sendBytes = Encoding.ASCII.GetBytes("REGISTERED " + remoteEndPoint.ToString());
server.Send(sendBytes, sendBytes.Length, remoteEndPoint);
handleClinet client = new handleClinet();
clientsList.Add(data, server);
client.startClient(server, data, clientsList, remoteEndPoint);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
//break;
}
}
}
//Broadcast method is used to send message to ALL clients
public static void broadcast(UdpClient dest, string msg, string uName, bool flag, IPEndPoint sendEP)
{
foreach (DictionaryEntry Item in clientsList)
{
Byte[] broadcastBytes = null;
if (flag == true)
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}
else
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}
dest.Send(broadcastBytes, broadcastBytes.Length, sendEP);
}
}
}//end Main class
}
public class handleClinet
{
UdpClient clientSocket;
string clNo;
Hashtable clientsList;
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
IPEndPoint myEP = new IPEndPoint(IPAddress.Any, 0);
public void startClient(UdpClient inClientSocket, string clineNo, Hashtable cList, IPEndPoint tempEP)
{
this.myEP = tempEP;
this.clientSocket = inClientSocket;
this.clNo = clineNo;
this.clientsList = cList;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat()
{
int requestCount = 0;
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
byte[] received = clientSocket.Receive(ref remoteIPEndPoint);
dataFromClient = Encoding.ASCII.GetString(received);
Console.WriteLine(dataFromClient);
rCount = Convert.ToString(requestCount);
if (dataFromClient.Contains("DEREGISTER"))
Program.broadcast(clientSocket, "DREG-CONF", clNo, true, myEP);
else
Program.broadcast(clientSocket, dataFromClient, clNo, true, myEP);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
break;
}
}//end while
}//end doChat
} //end class handleClinet
}

Related

C# TCP client connect to server

I am working on a Master - Slave kind of network relationship between a server and multiple clients.
The server is fine, the problem is that i am new to TCP and do not know how to connect to the server without the client knowing the ip form the start.
If someone could rewrite some of my code so it works, I would be thankful.
The server
namespace Server
{
class Program
{
static void Main(string[] args)
{
TcpListener listen = new TcpListener(IPAddress.Any, 8001);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
listen.Start();
Console.WriteLine(" >> " + "Server Started");
while (true)
{
counter += 1;
clientSocket = listen.AcceptTcpClient();
HandleClinet client = new HandleClinet();
client.startClient(clientSocket, Convert.ToString(counter));
}
}
}
public class HandleClinet
{
TcpClient clientSocket;
string clNo;
public void startClient(TcpClient inClientSocket, string clineNo)
{
clientSocket = inClientSocket;
clNo = clineNo;
Thread ClientThread = new Thread(DoChat);
ClientThread.Start();
}
private void DoChat()
{
byte[] bytesFrom = new byte[1024];
string dataFromClient = null;
byte[] sendBytes = null;
string serverResponse = null;
while ((true))
{
try
{
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, 1024);
dataFromClient = Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("\0"));
Console.WriteLine(" >> " + "From client-" + clNo + " " + dataFromClient);
serverResponse = Console.ReadLine();
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
}
catch (Exception ex)
{
throw;
}
}
}
}
}
The client
namespace Client
{
class Program
{
public static TcpClient tcpclnt = new TcpClient();
static void Main(string[] args)
{
while(true)
{
LoopConnect();
LoopPacket();
tcpclnt.Close();
}
}
private static void LoopPacket()
{
byte[] bytesFrom = new byte[1024];
string dataFromClient = null;
byte[] sendBytes = null;
string serverResponse = null;
while ((true))
{
try
{
NetworkStream networkStream = tcpclnt.GetStream();
serverResponse = "Give me a command!";
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Read(bytesFrom, 0, 1024);
dataFromClient = Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("\0"));
Console.WriteLine(" >> " + "From server -" + dataFromClient);
networkStream.Flush();
}
catch (Exception ex)
{
throw;
}
}
}
private static void LoopConnect()
{
Console.WriteLine("Connecting.....");
while(true)
{
try
{
tcpclnt.Connect(IPAddress.Any, 8001); // The problem area
break;
}
catch (Exception)
{
Console.Write(".");
}
}
Console.WriteLine("Connected.");
}
}
}
The client should somehow get address of the server. The method is depending on the network type (local or Internet). In case of Internet it's virtually impossible without some known peer. In case of a local network you could use a broadcast UDP request (this method is depending on the local network routing rules).

Multi-threaded TCP Server with high CPU and keep increase thread count

I wrote simple Multi-Threaded TCP C# Server program.After I run my program I got high CPU usage and thread count is keep increasing in task manager. Can anyone help me to figure out how to solve and give suggestions?
This is my code.
public class Program
{
static void Main(string[] args)
{
int _Port = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TCPPort"]);
string _IP = System.Configuration.ConfigurationManager.AppSettings["TCPIP"];
TcpServer server = new TcpServer(_Port);
}
}
public class TcpServer
{
private TcpListener _server;
private Boolean _isRunning;
private static int defaultMax = 8;
public TcpServer(int port)
{
_server = new TcpListener(IPAddress.Any, port);
_server.Start();
_isRunning = true;
LoopClients();
}
public void LoopClients()
{
while (_isRunning)
{
TcpClient newClient = _server.AcceptTcpClient();
SentFirstTimeData_New(newClient);
Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
t.Start(newClient);
}
}
public void HandleClient(object obj)
{
int requestCount = 0;
byte[] bytesFrom = new byte[209666];
string dataFromClient = null;
Byte[] sendBytes = null;
requestCount = 0;
int byteread = 0;
string respdata = string.Empty;
byte[] buffer = new byte[4096];
int numberOfBytesRead;
TcpClient client = (TcpClient)obj;
NetworkStream networkStream = client.GetStream();
IPAddress address = ((IPEndPoint)client.Client.RemoteEndPoint).Address;
Boolean bClientConnected = true;
int id = Thread.CurrentThread.ManagedThreadId;
while (bClientConnected)
{
try {
if (networkStream.DataAvailable)
{
byteread = networkStream.Read(bytesFrom, 0, (int)client.ReceiveBufferSize);
dataFromClient = Encoding.ASCII.GetString(bytesFrom).TrimEnd('\0');
System.Text.Encoding.ASCII.GetString(bytesFrom);
XmlDocument doc = new XmlDocument();
string xml = Encoding.UTF8.GetString(bytesFrom).TrimEnd('\0');
doc.LoadXml(xml);
XElement incc = XElement.Load(new XmlNodeReader(doc));
respdata = AysncTCPIncomeString(incc);
sendBytes = Encoding.ASCII.GetBytes(respdata);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
}
}
catch (Exception ex)
{
Helper.WriteLog("Exception=" + ex.Message);
}
}
}
public void SentFirstTimeData_New(TcpClient tc)
{
try
{
int threadid = Thread.CurrentThread.ManagedThreadId;
string Msg = HLStatusResponse.FirstTimeStatusSuccessfulResponse("STATUS", "1");
NetworkStream _NetworkStream = tc.GetStream();
if (_NetworkStream != null)
{
byte[] data = Encoding.ASCII.GetBytes(Msg);
_NetworkStream.Write(data, 0, data.Length);
Helper.WriteLog("ThreadId=" + threadid.ToString() + ";SentFirstTimeData :\t " + Msg);
}
}
catch (Exception ex)
{
Helper.WriteLog("Sent Though Tcp Eror :" + ex.ToString());
}
}
}
Consider this chunk of code:
Boolean bClientConnected = true;
int id = Thread.CurrentThread.ManagedThreadId;
while (bClientConnected)
{
try {
if (networkStream.DataAvailable)
You never change bClientConnected - it is always true, so your loop never exits.
Also, if the connection is idle - that is, if networkStream.DataAvailable is false - then you just spin in your while loop doing nothing.
If you have a thread per client, why don't you just let the thread be blocked by performing a read from the socket? Then the thread won't spin wasting cpu doing nothing.

Acquiring client's IP using IPAddress.Any

I am currently working on a simple udp client/server system, and I stumbled upon the following: When I try to get the IP of IPEndPoint (which I fetched using IPAdress.Any)in a program using UdpClient it works and I get the following result (the top one):
But when I use a normal socket instead of a UdpClient it somehow fails to distinguish the clients/IPs (bottom one). The code for both is listed below. The reason I would like to use sockets is because using the same class for both sending and receiving (not the same instance) is convenient and makes the code far more understandable.
First
bool messageReceived = false;
bool done = false;
const int listenPort = 11000;
UdpClient listener = new UdpClient(listenPort);
IPEndPoint receiveEP = new IPEndPoint(IPAddress.Any, listenPort);
string[] adresses = new string[2];
public void ReceiveCallback(IAsyncResult ar)
{
int id = 0;
Byte[] receiveBytes = listener.EndReceive(ar, ref receiveEP);
for (int i = 0; i < adresses.Length; i++)
{
if (adresses[i] == receiveEP.Address.ToString())
{
id = i;
break;
}
else if (adresses[i] == null)
{
id = i;
adresses[i] = receiveEP.Address.ToString();
break;
}
}
byte[] a= Encoding.ASCII.GetBytes("Is anybody there?");
listener.Send(a, a.Length, receiveEP);
Console.WriteLine("Received message from {0} (client {1}):", adresses[id],id);
string receiveString = Encoding.ASCII.GetString(receiveBytes);
if (receiveString == "stop")
{
done = true;
}
Console.WriteLine("Received: {0}", receiveString);
messageReceived = true;
}
public void ReceiveMessages()
{
Console.WriteLine("listening for messages");
while(!done){
try
{
messageReceived = false;
if (!messageReceived)
{
listener.BeginReceive(new AsyncCallback(ReceiveCallback), null);
}
while (!messageReceived)
{
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Console.WriteLine("Done receiving messages...");
for (int i = 0; i < adresses.Length; i++)
{
if (adresses[i] != null)
{
Console.WriteLine(adresses[i]);
}
}
Console.ReadLine();
listener.Close();
}'
Second
bool messageReceived = false;
bool done = false;
const int listenPort = 11000;
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
IPEndPoint receiveEP = new IPEndPoint(IPAddress.Any, listenPort);
string[] adresses = new string[2];
byte[] buffer = new byte[1024];
public void ReceiveMessages()
{
listener.Bind(receiveEP);
Console.WriteLine("listening for messages");
while (!done)
{
try
{
messageReceived = false;
if (!messageReceived)
{
listener.BeginReceive(buffer, 0,1024,SocketFlags.None,new AsyncCallback(ReceiveCallback), null);
}
while (!messageReceived)
{
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
Console.WriteLine("Done receiving messages...");
for (int i = 0; i < adresses.Length; i++)
{
if (adresses[i] != null)
{
Console.WriteLine(adresses[i]);
}
}
Console.ReadLine();
listener.Close();
}
public void ReceiveCallback(IAsyncResult ar)
{
int id = 0;
int read = listener.EndReceive(ar);
for (int i = 0; i < adresses.Length; i++)
{
if (adresses[i] == receiveEP.Address.ToString())
{
id = i;
break;
}
else if (adresses[i] == null)
{
id = i;
adresses[i] = receiveEP.Address.ToString();
break;
}
}
Console.WriteLine("Received message from {0} (client {1}):", adresses[id], id);
string receiveString = Encoding.ASCII.GetString(buffer,0,read);
if (receiveString == "stop")
{
done = true;
}
Console.WriteLine("Received: {0}", receiveString);
messageReceived = true;
}'
I've already tried Socket.ReceiveMessageFrom() and using the packetinfo it returned but I ended up with the ip4 of the server even when I send from another machine. Could someone help me out?
Even though this was never supposed to be a Q/A type of question, I've found a way of getting it to work, which means receive() changes the groupEP to the IP of the data packet's sender by just using a Socket instead of an UdpClient (I mimicked the way an UdpClient works). At the moment, it's still synchronous (listener.Receive() is a blocking call) but that will be changed in the near future:
private const int listenPort = 11000;
public static int Main()
{
bool done = false;
Listener listener = new Listener(listenPort);
IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
byte[] buffer = new byte[2048];
string received_data;
try
{
while (!done)
{
Console.WriteLine("Waiting for broadcast");
buffer=listener.Receive(ref groupEP);
received_data = Encoding.ASCII.GetString(buffer);
Console.WriteLine("Received a broadcast from {0}: {1}", groupEP.ToString(), received_data);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
return 0;
}
}
public class Listener
{
public Socket client;
public AddressFamily adressFamily;
byte[] byte_buffer = new byte[2048];
public int port;
public Listener(int p)
{
port=p;
adressFamily = AddressFamily.InterNetwork;
IPEndPoint localEP;
localEP = new IPEndPoint(IPAddress.Any, port);
client = new Socket(this.adressFamily, SocketType.Dgram, ProtocolType.Udp);
client.Bind(localEP);
}
public byte[] Receive(ref IPEndPoint remoteEP)
{
IPEndPoint ipEndPoint=new IPEndPoint(IPAddress.Any,port);
EndPoint endPoint = (EndPoint)ipEndPoint;
int num = client.ReceiveFrom(byte_buffer, 2048, SocketFlags.None, ref endPoint);
remoteEP = (IPEndPoint)endPoint;
if (num < 2048)
{
byte[] array = new byte[num];
Buffer.BlockCopy(byte_buffer, 0, array, 0, num);
return array;
}
return byte_buffer;
}

Multithreaded UDP client/server C#

I am trying to get a multi-threaded UDP client/server going, but i'm running into problems on the server side. When a client attempts to register, a thread is created and all the interactions for that client are handled in that thread, but for some reason it only enters the thread once then exits right away.. can anyone help figure out why this happens? -Thanks in advance..
namespace AuctionServer
{
class Program
{
public static Hashtable clientsList = new Hashtable();
static void Main(string[] args)
{
//IPAddress ipAd = IPAddress.Parse("255.255.255.255");
UdpClient server = new UdpClient(8888);
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
string data = "";
int listSize = 0;
Console.WriteLine("Auction Server Started ....");
listSize = clientsList.Count;
while (true)
{
//Reads data
byte[] inStream = server.Receive(ref remoteEndPoint);
data = Encoding.ASCII.GetString(inStream);
//Console.WriteLine("REGISTER " + remoteEndPoint);
if (!data.Contains("DEREGISTER "))
{
byte[] sendBytes = Encoding.ASCII.GetBytes(data + remoteEndPoint.ToString());
server.Send(sendBytes, sendBytes.Length, remoteEndPoint);
handleClinet client = new handleClinet();
Console.WriteLine(data);
clientsList.Add(data, server);
client.startClient(server, data, clientsList, remoteEndPoint);
data = "";
}
}
}
//Broadcast method is used to send message to ALL clients
public static void broadcast(UdpClient dest, string msg, string uName, bool flag, IPEndPoint sendEP, Hashtable clientsList)
{
foreach (DictionaryEntry Item in clientsList)
{
Byte[] broadcastBytes = null;
if (flag == true)
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}
else
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}
dest.Send(broadcastBytes, broadcastBytes.Length, sendEP);
}
}
}//end Main class
}
namespace AuctionServer
{
public class handleClinet
{
UdpClient clientSocket;
string clNo;
Hashtable clientsList;
IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);
IPEndPoint myEP = new IPEndPoint(IPAddress.Any, 0);
public void startClient(UdpClient inClientSocket, string clineNo, Hashtable cList, IPEndPoint tempEP)
{
this.myEP = tempEP;
this.clientSocket = inClientSocket;
this.clNo = clineNo;
this.clientsList = cList;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat()
{
int requestCount = 0;
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
//Thread.Sleep(1000);
if (requestCount == 0)
{
Console.WriteLine("Thread Created");
requestCount++;
}
byte[] received = clientSocket.Receive(ref remoteIPEndPoint);
dataFromClient = Encoding.ASCII.GetString(received);
Console.WriteLine(dataFromClient);
if (dataFromClient.Contains("DEREGISTER"))
clientSocket.Send(received, received.Length, remoteIPEndPoint);
//Program.broadcast(clientSocket, "DREG-CONF", clNo, true, myEP, clientsList);
//else
// Program.broadcast(clientSocket, dataFromClient, clNo, true, myEP, clientsList);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadKey();
break;
}
}//end while
}//end doChat
}
The two loops run on different threads. So the loop in Main() is executing concurrently with the loop in your handleClinet class.
If you want to switch to the handleClinet class's loop and debug it, then use the Threads window in the debugger (Debug menu, Windows menu item, then Threads...or press Ctrl-D, T) to switch to that thread. Then you can see the call stack and state of that thread.
Note that this may not work on the Express version of Visual Studio. I haven't tried the most recent version, but past versions did not support the Threads window. (You can still debug a specific thread by setting a breakpoint thereā€¦it's just that you can't switch to the thread manually).

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