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;
}
}
}
}
Related
So i got this multi thread tcp server code, it is working great, but i can not switch between clients.
So my question is how can i switch between clients?
I am planing to switch the server to winforms but i do not know how to access other threads.
Also, please tell what should i improve and better ways of sanitizing user input.
Here is the server code:
using System;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
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);
//---prepare client counter---
int num = 0;
//---announce and start listening---
Console.WriteLine("Listening...");
listener.Start();
while (true)
{
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
//---add 1 to total clients---
num = num + 1;
//---check if current thread name is null, if yes set the current client position---
if (Thread.CurrentThread.Name == null)
{
Thread.CurrentThread.Name = num.ToString();
}
else
{
Console.WriteLine("Unable to name a previously " +
"named thread.");
}
string clientip = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
//---write that client connected and write its ip---
Console.WriteLine("Client connected: [IP: {0}, Client: {1}]", clientip, Thread.CurrentThread.Name);
//---loop for infinite amount of time---
while (true)
{
try
{
//---Make thread background---
Thread.CurrentThread.IsBackground = true;
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
new Thread(() =>
{
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("[IP: {0}, Client: {1}]: " + dataReceived, clientip, Thread.CurrentThread.Name);
}).Start();
//---write back the text to the client---
Console.WriteLine("Enter data to send back to [IP: {0}, Client: {1}]: ", clientip, Thread.CurrentThread.Name);
//---read user input---
string input = Console.ReadLine();
//---sanitize user input---
if (input == String.Empty)
{
input = #" ";
}
if (input == #"")
{
input = #" ";
}
if (input == null)
{
input = #" ";
}
//---convert ASCII text to bytes---
byte[] send = Encoding.ASCII.GetBytes(input);
//---write bytes to network stream---
nwStream.Write(send, 0, send.Length);
}
catch (Exception)
{
//---close client---
client.Close();
//---Announce disconnect---
Console.WriteLine("Client disconnected [IP: {0}, Client: {1}]", clientip, Thread.CurrentThread.Name);
//---remove 1 from total clients---
num = num - 1;
//---Abort current thread---
Thread.CurrentThread.Abort();
return;
}
}
}).Start();
}
}
}
}
This is the code for client:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
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 = "Received the text.";
//---create a TCPClient object at the IP and port no.---
TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
while (true)
{
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));
}
client.Close();
}
}
}
Hi i have the following socket server/client codes which another stackoverflow member gave me.
Basically the server listens to multiple clients, it all works good and smooth but when a client exits the app the server crashes because of unexpected disconnect.
I read about heartbeed but don't know how to implement it as im quite a noob at c#
Below are the codes
Server:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class AsynchIOServer
{
static System.Collections.Concurrent.ConcurrentBag<Socket> ConnectedClients = new System.Collections.Concurrent.ConcurrentBag<Socket>();
static void Process(Socket client)
{
Console.WriteLine("Incoming connection from " + client.RemoteEndPoint);
const int maxMessageSize = 1024;
byte[] response;
int received;
while (true)
{
if (client.Poll(-1, SelectMode.SelectRead))
{
// Receive message from the server:
response = new byte[maxMessageSize];
received = client.Receive(response);
if (received == 0)
{
Console.WriteLine("Client closed connection!");
if (!ConnectedClients.TryTake(out client))
Console.WriteLine("Error when removing connection socket object from list (" + client.RemoteEndPoint + ")!");
return;
}
List<byte> respBytesList = new List<byte>(response);
respBytesList.RemoveRange(received, maxMessageSize - received); // truncate zero end
Console.WriteLine("Client " + client.RemoteEndPoint + " : " + Encoding.ASCII.GetString(respBytesList.ToArray()));
}
}
}
public static void Main()
{
int backlog = -1, port = 2222;
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.ReceiveTimeout = -1;
// Start listening.
try
{
server.Bind(new IPEndPoint(IPAddress.Any, port));
server.Listen(backlog);
}
catch (Exception)
{
Console.WriteLine("Listening failed!");
Console.ReadKey();
return;
}
Console.WriteLine("Start listening...");
new System.Threading.Thread(() => {
while (true)
{
Socket client = server.Accept();
ConnectedClients.Add(client);
new System.Threading.Thread(() => {
try { Process(client); }
catch (Exception ex)
{
Console.WriteLine(client.RemoteEndPoint + " client connection processing error: " + ex.Message);
if (!ConnectedClients.TryTake(out client))
Console.WriteLine("Error when removing connection socket object from list (" + client.RemoteEndPoint + ")!");
}
}).Start();
}
}).Start();
while (true)
{
byte[] sent = Encoding.ASCII.GetBytes(Console.ReadLine());
if (sent.Length == 0) break;
foreach (Socket s in ConnectedClients.ToArray()) s.Send(sent);
}
Console.WriteLine("Press any key for exit...");
foreach (Socket s in ConnectedClients.ToArray()) s.Close();
Console.ReadKey();
}
}
Client:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class Client
{
static void WorkWithServer(Socket server)
{
const int maxMessageSize = 1024;
byte[] response;
int received;
while (true)
{
try
{
// Receive message from the server:
response = new byte[maxMessageSize];
received = server.Receive(response);
if (received == 0)
{
Console.WriteLine("Server closed connection.");
return;
}
List<byte> respBytesList = new List<byte>(response);
respBytesList.RemoveRange(received, maxMessageSize - received); // truncate zero end
Console.WriteLine("Server: " + Encoding.ASCII.GetString(respBytesList.ToArray()));
// Send message to the server:
/* Console.Write("You: ");
server.Send(Encoding.ASCII.GetBytes(Console.ReadLine()));
Console.WriteLine(); */
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
return;
}
}
}
static public void Main(string[] Args)
{
IPEndPoint serverEp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2222);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.ReceiveTimeout = -1;
// Connect to the server.
try { server.Connect(serverEp); }
catch (Exception)
{
Console.WriteLine("Establish connection with server (" + serverEp + ") failed!");
Console.ReadKey();
return;
}
Console.WriteLine("Connection with server (" + serverEp + ") established!");
WorkWithServer(server);
Console.WriteLine("Press any key for exit...");
Console.ReadKey();
}
}
Apart from that i want the server to receive data from another server and once received transmit it to all the connected clients
I know i am probabily asking for too much but as i said my c# skills are almost none and i cannot afford paying someone
I'm making a simple chat application using TcpClient and TcpServer from System.Net.
I got everything working on my PC, the server communicates with the client and vice versa. But when I try to connect to the same server application using another PC (even on the same subnet as my PC) the thing doesn't work.
I've tried port-forwarding through my router, firewall and still nothing.
The Can you see me website says that the connection is being refused. Although!! Sometimes it says that the connection is timed out completely.
I am not sure what's wrong with my code or my PC, I would really appreciate some help from people that are more experienced in this area than I am.
Here is the configuration for the port forwarding in my router:
If you need the code for the client and the server, here they are:
P.S. I make the change to the client in the BeginConnect() part at the bottom in order to change the IP address that I'm connecting to
Client:
using System;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
namespace TcpTest_Client_
{
public partial class Form1 : Form
{
TcpClient client;
IPAddress localIP = null;
bool connected = false;
public Form1()
{
InitializeComponent();
}
public void clientConnectCallback(IAsyncResult result)
{
try
{
client.EndConnect(result);
Log("Connected to " + client.Client.RemoteEndPoint);
connected = true;
NetworkStream clientStream = client.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch (Exception ex)
{
//a socket error has occured
Log(ex.Message);
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
Log("Server on has disconnected");
break;
}
//message has successfully been received
UTF8Encoding encoder = new UTF8Encoding();
string bufferincmessage = encoder.GetString(message, 0, bytesRead);
Log("Server: " + bufferincmessage);
}
}
catch (Exception ex)
{
Log(ex.Message);
}
}
public void Log(string msg)
{
richTextBox1.BeginInvoke(new Action(
() =>
{
richTextBox1.Text += msg + "\n";
}));
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (IPAddress addr in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (addr.AddressFamily == AddressFamily.InterNetwork)
{
localIP = addr;
break;
}
}
client = new TcpClient(AddressFamily.InterNetwork);
}
private void button2_Click(object sender, EventArgs e)
{
try
{
client.BeginConnect(IPAddress.Parse("109.252.107.144"), 1234, clientConnectCallback, client);
}
catch (Exception ex)
{
Log(ex.Message);
}
}
private void button1_Click(object sender, EventArgs e)
{
if (connected)
{
UTF8Encoding encoder = new UTF8Encoding();
NetworkStream clientStream = client.GetStream();
byte[] stringToSend = new byte[richTextBox2.Text.Length];
stringToSend = encoder.GetBytes(richTextBox2.Text);
clientStream.Write(stringToSend, 0, stringToSend.Length);
}
}
}
}
Server:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace TcpTest
{
public partial class Form1 : Form
{
private TcpListener server;
private List<Thread> clientThreads = null;
public Thread MainThread;
public Form1()
{
InitializeComponent();
}
public void Log(string msg)
{
richTextBox1.BeginInvoke(new Action(
() =>
{
richTextBox1.Text += msg + "\n";
}));
}
public static string bufferincmessage;
public void AcceptSocketPackets(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch (Exception ex)
{
//a socket error has occured
Log(ex.Message);
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
Log("Client on " + tcpClient.Client.RemoteEndPoint + " has disconnected from the server");
break;
}
//message has successfully been received
UTF8Encoding encoder = new UTF8Encoding();
bufferincmessage = encoder.GetString(message, 0, bytesRead);
Log("Client from " + tcpClient.Client.RemoteEndPoint + ": " + bufferincmessage);
string stringToSend = "You sent me: " + bufferincmessage;
byte[] messageToSend = new byte[stringToSend.Length];
messageToSend = encoder.GetBytes(stringToSend);
clientStream.Write(messageToSend, 0, messageToSend.Length);
}
}
public void SocketAcceptCallback(IAsyncResult result)
{
TcpClient newClient = server.EndAcceptTcpClient(result);
Log("Accepted client on " + newClient.Client.RemoteEndPoint);
clientThreads.Add(new Thread(new ParameterizedThreadStart(AcceptSocketPackets)));
clientThreads[clientThreads.Count - 1].Start(newClient);
server.BeginAcceptTcpClient(SocketAcceptCallback, server);
}
private void Form1_Load(object sender, EventArgs e)
{
MainThread = Thread.CurrentThread;
clientThreads = new List<Thread>();
try
{
IPAddress localIP = null;
foreach (IPAddress addr in Dns.GetHostAddresses(Dns.GetHostName()))
{
if (addr.AddressFamily == AddressFamily.InterNetwork)
{
localIP = addr;
break;
}
}
localIP = IPAddress.Any;
// could also use this:
// server = new TcpListener(new IPEndPoint(IPAddress.Any, 1234));
server = new TcpListener(new IPEndPoint(localIP, 1234));
Log("Starting server on " + localIP + ":1234");
server.Start(6);
server.BeginAcceptTcpClient(SocketAcceptCallback, server);
Log("Started server on " + localIP + ":1234");
}
catch (Exception ex)
{
Log(ex.Message);
}
}
}
}
C++ is giving me problems like that. Try creating another project, paste the server code and build it as Release x86. If you change the build target and our problem is the same, windows firewall, even when turned off, won't allow the server or the client to run without any exception. If it doesn't work I might not know the answer.
I have a GPS Tracker Device, I have run a TCP/IP Server Code which Successfully establishes connection with each device in a separate Thread and Device Keep sending its heart beat after one minute and server replies ON. When I send a command to get device location it gives me location and everything is working fine.
Now I want to get location from an android device using web service, Now I'm confuse how can I use running thread of a specific device from an Android App?
class Server
{
TcpListener server = null;
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 a connection... ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
Thread t = new Thread(new ParameterizedThreadStart(HandleDeivce));
t.Start(client);
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
}
public void HandleDeivce(Object obj)
{
TcpClient client = (TcpClient)obj;
NetworkStream stream = client.GetStream();
string data = null;
Byte[] bytes = new Byte[256];
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("{1}: Received: {0}", data, Thread.CurrentThread.ManagedThreadId);
if (data.StartsWith("##"))
{
data = "LOAD";
}
else
{
data = "ON";
}
byte[] msg = Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
Console.WriteLine("{1}: Sent: {0}", data, Thread.CurrentThread.ManagedThreadId);
}
client.Close();
}
}
Try making code look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ConsoleApplication16
{
class Program
{
const string IP = "123.456.789.000";
const int PORT_NUMBER = 1234;
static AutoResetEvent autoEvent = new AutoResetEvent(false);
static void Main(string[] args)
{
GPSClient client = new GPSClient(IP, PORT_NUMBER);
//start http client or equivalent here
while (true)
{
autoEvent.Reset();
autoEvent.WaitOne();
//wait for message from user/client on service port
string message = client.message;
//send message back to user/client
}
}
}
public class WebServer
{
}
public class GPSClient
{
const int BUFFER_SIZE = 256;
TcpClient client = null;
NetworkStream stream = null;
Byte[] bytes = new Byte[BUFFER_SIZE];
public string message { get; set; }
public GPSClient(string ip, int port)
{
try
{
Console.WriteLine("Connecting to Device... ");
client.Connect(ip, port);
Console.WriteLine("Connected!");
stream = client.GetStream();
stream.BeginRead(bytes, 0, BUFFER_SIZE, new AsyncCallback(HandleDeivce), stream);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
}
public void HandleDeivce(IAsyncResult ar)
{
NetworkStream stream = ar.AsyncState as NetworkStream;
string data = null;
int i = stream.Read(bytes, 0, BUFFER_SIZE);
data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
message = data;
if (data.StartsWith("##"))
{
data = "LOAD";
}
else
{
data = "ON";
}
byte[] msg = Encoding.ASCII.GetBytes(data);
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
stream.BeginRead(bytes, 0, BUFFER_SIZE, new AsyncCallback(HandleDeivce), stream);
}
}
}
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.