Client send message server not received message in tcp/ip socket program - c#

TCP/IP socket program client send text server receive and store database table. I'm righting code below but i have error text reeving time.
This is Client Side Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using System.IO;
namespace ClientApplication
{
class Client
{
static void Main(string[] args)
{
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
//tcpclnt.Connect("162.144.85.232", 8080);
tcpclnt.Connect("162.144.85.232", 4489);
Console.WriteLine("Connected");
Console.Write("Enter the string to be Sent : ");
String str = Console.ReadLine();
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
System.Net.ServicePointManager.Expect100Continue = false;
Console.WriteLine("Sending.....");
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]));
Console.ReadLine();
tcpclnt.Close();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
Console.ReadLine();
}
}
}
}
This Is Server Side Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace ServerApplication
{
class Server
{
static void Main(string[] args)
{
try
{
IPAddress ipadd = IPAddress.Parse("192.168.1.7");
TcpListener list = new TcpListener(ipadd, 8080);
list.Start();
Console.WriteLine("The server is running at port 8080...");
Console.WriteLine("The Local End point Is:" + list.LocalEndpoint);
System.Net.ServicePointManager.Expect100Continue = false;
Socket s = list.AcceptSocket();
Console.WriteLine("Connections Accepted from:" + s.RemoteEndPoint);
byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("Recived...");
for (int i = 0; i < k; i++)
Console.WriteLine(Convert.ToChar(b[i]));
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The String Was Recived throw Server"));
Console.WriteLine("\n Sent Acknowlegment");
s.Close();
list.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
}
I'm trying to execute this code i have error happen like this
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. Please resolve my issue .

There are a number of problems with the code you posted, but the one directly causing the behavior you're seeing is that the server closes the socket without waiting for the client to finish reading from the connection.
Look up "TCP graceful shutdown" for more information. In the meantime, the following is an improvement on the code you posted and won't have that problem:
Server code:
class Server
{
static void Main(string[] args)
{
try
{
TcpListener list = new TcpListener(IPAddress.Any, 8080);
list.Start();
Console.WriteLine("The server is running at port 8080...");
Console.WriteLine("The Local End point Is:" + list.LocalEndpoint);
Socket s = list.AcceptSocket();
Console.WriteLine("Connections Accepted from:" + s.RemoteEndPoint);
byte[] b = new byte[100];
int k;
while ((k = s.Receive(b)) > 0)
{
Console.WriteLine("Recived...");
Console.WriteLine(Encoding.ASCII.GetString(b, 0, k));
s.Send(Encoding.ASCII.GetBytes("The String Was Recived throw Server"));
Console.WriteLine("\n Sent Acknowlegment");
}
s.Shutdown(SocketShutdown.Both);
s.Close();
list.Stop();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
Client code:
class Client
{
static void Main(string[] args)
{
try
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("192.168.1.7", 8080);
Console.WriteLine("Connected");
Console.Write("Enter the string to be Sent : ");
String str = Console.ReadLine();
Stream stm = tcpclnt.GetStream();
byte[] ba = Encoding.ASCII.GetBytes(str);
Console.WriteLine("Sending.....");
stm.Write(ba, 0, ba.Length);
tcpclnt.Client.Shutdown(SocketShutdown.Send);
byte[] bb = new byte[100];
int k;
while ((k = stm.Read(bb, 0, 100)) > 0)
{
Console.WriteLine(Encoding.ASCII.GetString(bb, 0, k));
}
Console.ReadLine();
tcpclnt.Close();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
Console.ReadLine();
}
}
}
The key thing here is that both server and client continue to read from the connection until the remote end has, by calling Socket.Shutdown(), signaled that there is no more data to be read.
I also removed the use of the System.Net.ServicePointManager.Expect100Continue property, which had no effect in this code. That only affects programs that use the ServicePoint class and is not useful here.
It's also not clear to me why for the client you use the NetworkStream instead of just getting the Client socket and using it directly. The NetworkStream object is useful when wrapping your I/O in e.g. StreamReader and StreamWriter, but here you're just using Stream.Read() and Stream.Write(), which have the exact same semantics as Socket.Receive() and Socket.Send(), respectively. In any case, note that while you are using the NetworkStream object for the send and receive, you still need to access the underlying Socket instance directly to correctly initiate the graceful shutdown (the endpoint not initiating could just close the NetworkStream, since it doesn't have to shutdown until it's done both sending and receiving).
I also cleaned up the handling of the ASCII-encoded text a bit.

Related

check when a client is disconnected

I have a console application in c#
this code can tell me when a client si connected in TCP to port 3001 and the message sent
I cant understand when he disconnects, its going into while (client.Connected) unlimited, i tried to check with a PING but sometimes returns false even if connnected,
I am stuck
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
int port = 3001;
TcpListener listener = new TcpListener(IPAddress.Any, port);
listener.Start();
Console.WriteLine("Listening on port " + port + "...");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Accepted connection from " + client.Client.RemoteEndPoint.ToString());
while (client.Connected)
{
NetworkStream stream = client.GetStream();
if (stream.DataAvailable)
{
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string data = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received data: " + data);
}
//check if client still connected
string[] cli = client.Client.RemoteEndPoint.ToString().Split(Convert.ToChar(":"));
string Host = cli[0];
int Uri = port;// int.Parse(cli[1]);
if (PingHost(Host,Uri)==false)
{
Console.WriteLine("Client disconnected.");
break;
}
}
}
}
public static bool PingHost(string hostUri, int portNumber)
{
try
{
using (var client = new TcpClient(hostUri, portNumber))
return true;
}
catch (SocketException ex)
{
//MessageBox.Show("Error pinging host:'" + hostUri + ":" + portNumber.ToString() + "'");
return false;
}
}
}
}

C# create multi threaded socket server and select client/connection

Currently, I'm programming in C#, I would like to modify the code below to isolate one client connection. so like creating a break-out room from the main pool.
Below are 2 files, one is just the basic standard .NET Framework Console App Program.cs file; the other is the server file. Combined, they both can make a multi-threaded server, but I would like one that allows me to also select a client to connect to in case if I were to create a remote control application as my friend did.
On a side note, I would like to share that I want to be able to connect to a client by entering connect [1,2,3,etc..] into the console.
Answers
If you answer, please put some code, It would really, really help. I learn a lot better by looking att the code rather than reading documentation.
Code
Server.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace TCPServer
{
class Server
{
TcpListener server = null;
int counter = 0;
public Server(string ip, int port)
{
IPAddress localAddr = IPAddress.Parse(ip);
server = new TcpListener(localAddr, port);
server.Start();
StartListener();
}
public void StartListener()
{
try
{
while (true)
{
Console.WriteLine("Waiting for incoming connections...");
TcpClient client = server.AcceptTcpClient();
counter += 1;
Console.WriteLine("Connected to authorized client: {0}", counter);
Thread t = new Thread(new ParameterizedThreadStart(HandleDeivce));
t.Start(client);
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
server.Stop();
}
}
public void HandleDeivce(Object obj)
{
TcpClient client = (TcpClient)obj;
var stream = client.GetStream();
string imei = String.Empty;
string data = null;
Byte[] bytes = new Byte[256];
int i;
try
{
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
string hex = BitConverter.ToString(bytes);
data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("{1}: Received: {0}", data, Thread.CurrentThread.ManagedThreadId);
if (data != "auth token")
{
stream.Close();
client.Close();
}
string str = "Device authorization successfull";
Byte[] reply = System.Text.Encoding.ASCII.GetBytes(str);
stream.Write(reply, 0, reply.Length);
Console.WriteLine("{1}: Sent: {0}", str, Thread.CurrentThread.ManagedThreadId);
}
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e.ToString());
client.Close();
}
}
}
}
Program.cs
using System;
using System.Threading;
namespace TCPServer
{
class Program
{
static void Main(string[] args)
{
Thread thread = new Thread(delegate()
{
Server server = new Server("127.0.0.1", 13000);
});
thread.Start();
Console.WriteLine("Server started...");
}
}
}

Error A connection attempt failed because the connected party did not properly repspond after a period of time

I am trying to establish a TCP connection using the console application, but the code that I am using produces an error.
I am able to ping the other device successfully from the PC.
Windows Firewall is off and there is no other active firewall on the computer.
The error I am getting is.
Error:
A connection attempt failed because the connected party did not
properly repspond after a period of time, or established connection
failed because connected host had failed to respond
Code:
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
while (true)
{
try
{
TcpClient tcpclnt1 = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt1.Connect("10.112.90.246", 13002);
// use the ipaddress as in the server program
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
String str = Console.ReadLine();
Stream stm = tcpclnt1.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]));
tcpclnt1.Close();
}
catch (Exception e)
{
Console.WriteLine("Error "+ e.Message + e.StackTrace);
}
}
}
}
}
I don't know what is wrong here.

how to send and receive string continously using sockets in c#

Basically what i am stuck at is , i want my client to send data continously and server to read from client as it sends, like when i send "2" it should read "2" and display and so on it should continue to read as long as i send from the client, i can stop or exit whenever i press some different character,.
what i have acheived is not continous, i send from client 2 and server receives 2 and then it is stopped, i want to send them continously , i am pasting below my code,
client.cs
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace Client
{
class Program
{
const int port = 8001;
const string ip = "127.0.0.1";
const int maxBuffer = 100;
static void Main(string[] args)
{
try
{
while (true)
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("127.0.0.1", 8001);
// use the ipaddress as in the server program
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
String str = Console.ReadLine();
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]));
Console.ReadLine();
tcpclnt.Close();
}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
}
server.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Server
{
class Program
{
const int port = 8001;
const string ip = "127.0.0.1";
const int maxBuffer = 100;
static void Main(string[] args)
{
try
{
IPAddress ipAd = IPAddress.Parse("127.0.0.1");
// use local m/c IP address, and
// use the same in the client
while (true)
{
/* 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...");
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(b[i]));
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("The string was recieved by the server."));
Console.WriteLine("\nSent Acknowledgement");
Console.ReadLine();
/* clean up */
s.Close();
myList.Stop();
}
}
catch (Exception e)
{
Console.WriteLine("Error..... " + e.StackTrace);
}
}
}
}
Any help will be appreciated
Thanks :)
By using MultiThread you can send and receive message between client and server continuously.
Server side example:
IPAddress[] ipAdd = Dns.GetHostAddresses("192.168.1.38");
IPAddress ipAddress = ipAdd[0];
TcpListener serverSocket = new TcpListener(ipAddress, 8888);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
notifyIcon.ShowBalloonTip(5000, "Server Notification", " >> Server Started.", wform.ToolTipIcon.Info);
counter = 0;
while (true)
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
if (clientsList.ContainsKey(dataFromClient))
{
continue;
}
else
{
clientsList.Add(dataFromClient, clientSocket);
}
string onlineUsers = "";
foreach (DictionaryEntry item in clientsList)
{
onlineUsers += item.Key.ToString() + ";";
}
onlineUsers = onlineUsers.Remove(onlineUsers.Length - 1);
Broadcast.BroadcastSend(dataFromClient + " joined. |" + onlineUsers, dataFromClient, ref clientsList, false, false);
notifyIcon.ShowBalloonTip(5000,"Client Notification", dataFromClient + " joined.", wform.ToolTipIcon.Info);
HandleClient client = new HandleClient();
client.StartClient(clientSocket, dataFromClient, clientsList, notifyIcon);
}
More details
Ignore my earlier answer
The problem is that the server is waiting for user response in console after sending acknowledgement.
Console.ReadLine();
Just comment out this line in your original program.
And add a exit condition by checking the input.
Also as the previous poster suggest, make it thread based if you want multiple clients connecting to this server simultaneously.

sending listbox value to console application using socket programming using c#

If I don't put a $ symbol at the end of string in the textbox it throws an error saying I have to make a change in the code so that whatever the user puts in the textbox it should be displayed. This is one scenario.
In my second scenario I need to send the number of selected items from the listbox to console.
How do I store selected values in a variable?
This is my client side code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Windows.Forms;
using System.Net.Sockets;
namespace eg_client
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
NetworkStream serverStream = clientSocket.GetStream();
string data = textBox2.Text;
byte[] dataB = System.Text.Encoding.Unicode.GetBytes(data);
serverStream.Write(dataB, 0, dataB.Length);
serverStream.Flush();
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
}
private void Form1_Load_1(object sender, EventArgs e)
{
clientSocket.Connect("127.0.0.1", 8001);
label2.Text = "Client Socket Program - Server Connected ...";
}
}
}
This is my server side code
using System;
using System.Net.Sockets;
using System.Text;
namespace eg_server
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8001);
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(" >> Server Started");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> Accept connection from client");
while ((true))
{
try
{
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine(" >> Data from client - " + dataFromClient);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> exit");
Console.ReadLine();
}
}
}
Can anyone help me on this?
Your server side code has
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
You have assumed the string will contain one, you need to decide what to do if the string does not have one.. such as
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
if (dataFromClient.Contains("$"))
{
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine(" >> Data from client - " + dataFromClient);
}
else
console.WriteLine("Data received in incorrect format");

Categories