I am trying to send message over TCP/IP in c# application using TCPClient and TCPListner classes
Following is my code which i got from codeproject site.
Client code written over btn click
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("192.168.0.102", 8001);
// use the ipaddress as in the server program
Console.WriteLine("Connected");
//Console.Write("Enter the string to be transmitted : ");
String str = textBox1.Text;
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error..... " + ex.Message);
}
Server code written on form_load
try
{
IPAddress ipAd = IPAddress.Parse("192.168.0.102");
// use local m/c IP address, and
// use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 8001);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" +
myList.LocalEndpoint);
Console.WriteLine("Waiting for a connection.....");
Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("Recieved...");
string str = string.Empty;
for (int i = 0; i < k; i++)
{
Console.Write(Convert.ToChar(b[i]));
str = str + Convert.ToChar(b[i]);
}
label1.Text = str;
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
/* clean up */
s.Close();
// myList.Stop();
}
Here on client, i m sending string written in textbox over tcp and it well recieved by server.
But when i trying to send another string, it fails without any exception and client application hangs for infinite time.
What is wrong here ?
Server should always be in listening mode, i.e the server code should be in while loop such that it can accept clients continuously. Your server will accept one client and then close itself. Therefore, if you click client's button, a new client tries to connect to server, but now the server won't be available.
Looking at the code you provided, the server only attempts to read 1 message from the client, so needs to be put in a loop to read the multiple incoming messages from the client, process the message and send response and then get more messages.
Note also that the server currently expects only one client to ever connect, processes that client and then closes.
The client is set up basically the same in the example, so you cant modify how one works without also modifying the other.
Related
So my TCP C# client server, an oddity is happening, when the server sends a message to a client running on localhost 127.0.0.1, the message goes through no problem, but when sending the message to a client running on another IPv4, the client and server connect but the message is received as null or zero. I am wondering why the message would come through no problem on localhost, but connect and then recieve a null message on a different ip though they connect?
Server code:
{
{
{
try
{
IPAddress ipAd = IPAddress.Parse(IPV4.Text); //use local m/c IP address, and use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 8001);
/* Start Listeneting at the specified port */
myList.Start();
MessageBox.Show("The server is running at port 8001...");
MessageBox.Show("The local End point is :" + myList.LocalEndpoint);
MessageBox.Show("Looking for other computer");
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
MessageBox.Show("The message " + satt.Text + " was sent to the computer with IP address " + IPV4.Text);
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
void ServerStart()
{
TcpListener listener = new TcpListener(IPAddress.Any, 8001);
listener.Start();
Console.WriteLine("Listening on port: 8001");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(state => HandleConnection(client));
void HandleConnection(TcpClient client)
{
Socket s = myList.AcceptSocket();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
Console.WriteLine("Number of connected buddies: " + connectedbuddies++);
client.Close();
string buddylist = myList.ToString();
socketlist = s.ToString();
slist = char.Parse(socketlist);
foreach (char slist in buddylist)
{
void HandleConnection(TcpClient client)
{
TcpListener myList = new TcpListener(ipAd, 8001);
/* Start Listeneting at the specified port */
myList.Start();
Console.WriteLine("Found buddy " + s.RemoteEndPoint);
while (connectedbuddies > 1)
{
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(satt.Text));
}
}
Console.WriteLine("Number of connected buddies: " + connectedbuddies++);
client.Close();
}
}
Client code:
try
{
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect(RecieveIPAdd.Text, 8001); // use the ipaddress as in the server program
MessageBox.Show("Connected");
Stream stm = tcpclnt.GetStream();
MessageBox.Show("Listening for information......");
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
string atk = Encoding.UTF8.GetString(bb.AsSpan(0, k));
Console.WriteLine($"Connected to server at IPv4 address {RecieveIPAdd.Text} Attack command Received: {atk}.
Thank you so much, I don't know why this would happen on an IP that is not localhost?
When I send the message to the client and I try to check it with an if statement it doesn't equal to what I sent from the server.
What I want to do is: I want to send the keyword (here it's poop) and check it with an if statement on the client part.
If it finds that keyword with the if statement I want to execute some code.
For example:
Client code:
try {
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("127.0.0.1",8001);
Console.WriteLine("Connected");
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen= new ASCIIEncoding();
while(true)
{
byte[] bb=new byte[100];
int k=stm.Read(bb,0,100);
for (int i=0;i<k;i++)
{
var msg = Convert.ToChar(bb[i]).ToString();
if(msg == "poop")
{
Console.WriteLine("Poop executed.");
}
}
}
}
catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
Server code (when the console reads my input I type "poop"):
try {
IPAddress ipAd = IPAddress.Parse("127.0.0.1");
TcpListener myList=new TcpListener(ipAd,8001);
myList.Start();
Console.WriteLine("The server is running at port 8001...");
Console.WriteLine("The local End point is :" +
myList.LocalEndpoint );
Console.WriteLine("Waiting for a connection.....");
Socket s=myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
ASCIIEncoding asen=new ASCIIEncoding();
while(true)
{
Console.Write("Msg to send: ");
var f = Console.ReadLine();
s.Send(asen.GetBytes(f));
}
s.Close();
myList.Stop();
}
catch (Exception e) {
Console.WriteLine("Error..... " + e.StackTrace);
}
The problem with your code is that you iterate over the byte array in which you wrote the received data. Therefore the message variable does always contain only one letter of your received message and is therefore never "poop" but "p", "o", "o", "p". To solve this issue you can use System.Text.Encoding to convert your byte array to a string:
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
var msg = System.Text.Encoding.UTF8.GetString(bb, 0, k);
if(msg == "poop")
{
// Do something
}
An even better solution would be to write back your received data into a temporary array until a defined end of string signal is received and only convert the temporary array if you are sure that everything is received.
In getting used to Sockets using Client server communication here is my code.
//server partl
try
{
IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //use local m/c IP address, and use the same in the client
/* Initializes the Listener */
TcpListener myList = new TcpListener(ipAd, 8020);
/* Start Listeneting at the specified port */
myList.Start();
Socket s = myList.AcceptSocket();
Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
//Console.WriteLine("Recieved...");
//Writes to label1
for (int i = 0; i < k; i++)
label1.Text = b[i].ToString();
//ASCII endoing to use ACK.
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
/* clean up */
s.Close();
myList.Stop();
}
catch (Exception ex)
{
Console.WriteLine("Error..... " + ex.StackTrace);
}
//Client part
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("127.0.0.1", 8020); // use the ipaddress as in the server program
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
//gets the text from textbox
String str = textBox1.Text;
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error..... " + ex.StackTrace);
}
}
I am using a form to communicate on local host and writing a one .cs file and want to show the text(from textbox) from Client-labelled portion to the label on server-labelled portion.
Any idea why its not showing output?. New to sockets !!!
When socket receives the data instead of loop simply use this:
if (k > 0)
label1.Text = Encoding.UTF8.GetString(b);
Also you can use this for simply send and receive data using TcpClient which is a wrapper around socket.
I have a simple implementation of a TCP client server relationship. But their are few problems that i don't know how to fix. here is the code of the Client and Server:
Client and Server are both separated. Each one of them is written i different project.
public void Server()
{
try
{
IPAddress IP = IPAddress.Parse("127.0.0.1");
TcpListener Listener = new TcpListener(IP, 8001);
Listener.Start();
Socket s = Listener.AcceptSocket();
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++){
ConsoleWpfGUI.Write(Convert.ToChar(b[i]));
}
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string:"+strTemp+ " was recieved by the server."));
s.Close();
Listener.Stop();
}
catch (Exception e) {
ConsoleWpfGUI.WriteLine("Error..... " + e.StackTrace);
}
}
}
public void Client()
{
try
{
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect("127.0.0.1", 8001);
String str = InputString.Text;
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
for (int i = 0; i < k; i++)
ConsoleWpfGUI.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
}
catch (Exception e)
{
ConsoleWpfGUI.Text = "No connection..... ";
}
}
}
1. The listener does not work properly, i.e. the listening captures the GUI thread (serv and client classes that i use in wpf). and not running in a separate thread, resulting with the application being unresponsive once “listen” (Buttoon that start the class serv) is pressed.
Only with the 1st call being replied it's work,the next send is fails. resulting not dealing with the socketing and passing to a separate thread right on the server side.
How can I use Thread that the serv class will not stuck the app.
And how i can use properly with socketing and passing threads that will make my app work more then ones.
Thanks!
You need to use separate threads for "Client" and "Server". You cannot run both in one UI thread. Because listening will block your UI thread and hence neither Client or Server can run correctly.
You can find many resources over internet about Client Server practice examples. Just use Threading, Background Workers for accomplish your task
Good Articles :
http://csharp.net-informations.com/communications/csharp-socket-programming.htm
http://www.codeproject.com/Tips/607801/SimpleplusChatplusprogramplusinplusC ,
http://www.codeproject.com/Articles/99143/BackgroundWorker-Class-Sample-for-Beginners
I ran your code. Try running following on TWO Console programs - Rub them Separately and run Server first
Client -
try
{
TcpClient tcpclnt = new TcpClient();
tcpclnt.Connect("127.0.0.1", 8001);
String str = "From CLient";
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));
tcpclnt.Close();
}
catch (Exception)
{
Console.WriteLine("No connection..... ");
}
Console.WriteLine("Transmission end.");
Console.ReadKey();
Server -
string strTemp = "Hello from server";
try
{
IPAddress IP = IPAddress.Parse("127.0.0.1");
TcpListener Listener = new TcpListener(IP, 8001);
Listener.Start();
Socket s = Listener.AcceptSocket();
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
{
Console.Write(Convert.ToChar(b[i]));
}
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string:" + strTemp + " was recieved by the server."));
s.Close();
Listener.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
Console.ReadKey();
Note - Just paste them inside Main method and try, you will need Sytem.IO import in Visual Studio ()
I am trying to send a request to an existing server solution and write out the results. The server is sending a total of 4 messages with my particular request but the number of messsages back can vary depending on the initial query.
I am able to successfully send the query to the server but when it comes to reading the response i can only read one message. The server logs show that 4 were sent back.
Please help.
IPHostEntry hostEntry = Dns.GetHostEntry(server_textbox.Text);
IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], port);
string data = String.Empty;
testclient = new TcpClient(server_textbox.Text, port);
testclient.ReceiveBufferSize = 1024;
testclient.SendBufferSize = 1024;
NetworkStream netStream = testclient.GetStream();
Byte[] message_byte = new System.Text.ASCIIEncoding().GetBytes(msg2);
netStream.Write(message_byte, 0, message_byte.Length);
Byte[] returnMessage = new byte[1024];
Int32 totalBytesReceived = 0;
Int32 bytesReceived = 0;
try
{
while ((bytesReceived = netStream.Read(returnMessage, totalBytesReceived, returnMessage.Length)) > 0)
{
totalBytesReceived += bytesReceived;
data += "\n" + ASCIIEncoding.ASCII.GetString(returnMessage);
bytesReceived = 0;
}
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
result_box.Text += data;
netStream.Close();
testclient.Close();
}
My guess is that all your messages are read in the first Read. When the server replies, all the data gets stuck in the windows receive buffer and gets read all at once.
I would recommend using Wireshark, which is more or less mandatory when doing network programming. You'll be able to see the 4 messages coming back from the server as at least 4 different tcp packets.