I have a stream coming in that varies in length but has a start and stop character. When I run this code:
public TCPListener()
{
Int32 port = 31001;
IPAddress localAddr = IPAddress.Parse("192.168.0.78"); //Local
server = new TcpListener(localAddr, port);
server.Start();
while (true)
{
// Console.Write("Waiting for a connection...-- ");
TcpClient client = server.AcceptTcpClient();
// Console.WriteLine("new client connected");
try
{
ThreadPool.QueueUserWorkItem(new WaitCallback(HandleClient), client);
}
catch (Exception ex)
{ }
}
}
private void HandleClient(object tcpClient)
{
// string path = #"c:\Test.txt";
TcpClient client = (TcpClient)tcpClient;
Byte[] bytes = new Byte[135];
String data = null;
int i;
try
{
NetworkStream stream = client.GetStream();
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
URLObject oU = new URLObject();
oU = oDecode.TextFrameDecode(data);
Console.WriteLine(data);
Console.WriteLine("");
}
}
catch (Exception ex)
{ }
// Console.WriteLine(data);
}
I get a lot of data every second; I get the data, but it's broken up sometimes into chunks that are not parsable. When I run this code to look for the end delimiter, the feed only get one connection every couple of minutes with only one record so I think the data is getting truncated which is not correct.
static void Main(string[] args)
{
Int32 port = 31001;
IPAddress localAddr = IPAddress.Parse("192.168.0.78"); //Local
server = new TcpListener(localAddr, port);
server.Start();
while (true)
{
Console.Write("Waiting for a connection...-- ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("new client connected");
try
{
ThreadPool.QueueUserWorkItem(new WaitCallback(HandleClient), client);
}
catch (Exception ex)
{ }
}
}
static void HandleClient(object tcpClient)
{
TcpClient client = (TcpClient)tcpClient;
Byte[] bytes = new Byte[135];
String data = null;
int i;
try
{
using (NetworkStream stream = client.GetStream())
using (StreamReader reader = new StreamReader(stream))
{
string inputLine = reader.ReadLineSingleBreak();
inputLine = inputLine + "#";
Console.WriteLine(inputLine);
URLObject oU = new URLObject();
oU = oDecode.TextFrameDecode(inputLine);
}
}
catch (Exception ex)
{ }
}
}
public static class StreamReaderExtensions
{
public static string ReadLineSingleBreak(this StreamReader self)
{
StringBuilder currentLine = new StringBuilder();
int i;
char c;
while ((i = self.Read()) >= 0)
{
c = (char)i;
if (c == '#')
{
break;
}
currentLine.Append(c);
}
return currentLine.ToString();
}
}
I need a mix of both... get all the data but then parse it correctly.
I did fix it by Pieter Witvoet advice:
static private TcpListener server = null;
static private Decode oDecode = new Decode();
static private string sLeftOver = string.Empty;
static void Main(string[] args)
{
Int32 port = 31001;
IPAddress localAddr = IPAddress.Parse("192.168.0.78"); //Local
server = new TcpListener(localAddr, port);
server.Start();
while (true)
{
Console.Write("Waiting for a connection...-- ");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("new client connected");
try
{
ThreadPool.QueueUserWorkItem(new WaitCallback(HandleClient), client);
}
catch (Exception ex)
{ }
}
}
static void HandleClient(object tcpClient)
{
TcpClient client = (TcpClient)tcpClient;
Byte[] bytes = new Byte[256];
String data = null;
int i;
try
{
NetworkStream stream = client.GetStream();
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
URLObject oU = new URLObject();
Console.WriteLine(data);
Console.WriteLine("");
//Split data here
string[] aData = Regex.Split(data, #"(?<=[#])");
foreach (string s in aData)
{
string sData = s;
sData = sLeftOver + sData;
if (sData.EndsWith("#"))
{
sLeftOver = string.Empty;
Console.WriteLine(sData);
Console.WriteLine("");
oU = oDecode.TextFrameDecode(sData);
}
else
{
sLeftOver = s;
}
}
}
}
catch (Exception ex)
{ }
}
Related
I use layered architecture. I create a server. I want the server to listen when the data arrives.
This is my server code in the DataAccess layer.
public class ServerDal : IServerDal
{
private TcpListener server;
private TcpClient client = new TcpClient();
public bool ServerStart(NetStatus netStatus)
{
bool status = false;
try
{
server = new TcpListener(IPAddress.Parse(netStatus.IPAddress), netStatus.Port);
server.Start();
status = true;
}
catch (SocketException ex)
{
Console.WriteLine("Starting Server Error..." + ex);
status = false;
}
return status;
}
public string ReceiveAndSend(NetStatus netStatus)
{
Byte[] bytes = new Byte[1024];
String data = null;
Mutex mutex = new Mutex(false, "TcpIpReceive");
mutex.WaitOne();
if (!client.Connected)
client = server.AcceptTcpClient();
try
{
NetworkStream stream = client.GetStream();
int i;
if ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: " + data);
}
}
catch (Exception ex)
{
Console.WriteLine("Connection Error..." + ex);
client.Close();
}
finally
{
mutex.ReleaseMutex();
}
return data;
}
}
I can listen to the client that first connects to the server. When the first connecting client disconnects, I can listen to the second connecting client.
I want to listen when both clients send data. How can I do that ? Thanks for your help.
I fixed the problem.
static List<TcpClient> tcpClients = new List<TcpClient>();
public void ReceiveMessage(NetStatus netStatus)
{
try {
TcpClient tcpClient = server.AcceptTcpClient();
tcpClients.Add(tcpClient);
Thread thread = new Thread(unused => ClientListener(tcpClient, netStatus));
thread.Start();
}
catch(Exception ex) {
Console.WriteLine("[ERROR...] Server Receive Error = {0} ", ex.Message);
}
}
public void ClientListener(object obj, NetStatus netStatus)
{
try
{
TcpClient tcpClient = (TcpClient)obj;
StreamReader reader = new StreamReader(tcpClient.GetStream());
while(true)
{
string message = null;
message = reader.ReadLine();
if(message!=null)
{
netStatus.IncommingMessage = message;
Console.WriteLine("[INFO....] Received Data = {0}", message);
}
}
}
catch(Exception ex)
{
Console.WriteLine("[ERROR....] ClientListener Error = {0}", ex.Message);
}
}
I have a problem with my chat app : it doesn't work over the network . I tried port-forwarding and other similar methods. I'm starting to question my code . I'm new to networking so please help me with this. I heard of another method using System.Net.Sockets but I haven't tried that yet . I heard that Sockets are pretty similar to TcpListener so I don't know what to say about this. I made sure I used the correct IP address , the AddressFamily.InterNetwork. Here is my code :
static TcpListener server;
public static void ListenThread()
{
TcpClient client = null;
NetworkStream stream = null;
ClientConnection currentClientConnection = new ClientConnection();
while (true)
{
if(client == null)
{
client = server.AcceptTcpClient();
stream = client.GetStream();
currentClientConnection = new ClientConnection(client, stream);
clients.Add(currentClientConnection);
currentConnections++;
// Logging
string text = "A Client connection establieshed ! Connections : " + currentConnections;
Console.WriteLine(text);
Logger.WriteToLog(text);
}
int bufferSize = client.ReceiveBufferSize;
byte[] buffer = new byte[bufferSize];
int i;
string data = null;
try
{
while ((i = stream.Read(buffer, 0, bufferSize)) != 0)
{
data = Encoding.ASCII.GetString(buffer, 0, i);
data = ProcessData(data);
if (data == "/disconnect")
{
clients.Remove(currentClientConnection);
currentConnections--;
// Logging
string text = "A user left the server ! Connections : " + currentConnections;
Console.WriteLine(text);
Logger.WriteToLog(text);
SendToAllClients(string.Format("[Server]>> A user left the chat!"), client);
client.Close();
stream.Close();
client = null;
break;
}
else
{
SendToAllClients(data, client);
}
}
}
catch { };
}
}
static void InitialiseServer()
{
Console.Write("Enter a port : ");
serverPort = int.Parse(Console.ReadLine());
Console.WriteLine();
IPAddress localMachineIP = GetLocalIPAddress();
try
{
Console.WriteLine("Initialising Server...");
server = new TcpListener(localMachineIP,serverPort);
Console.WriteLine("Server initialised !");
}
catch(Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
string text = string.Format("An error has occured while initalising server under IP={0} and port={1} . {2}", localMachineIP, serverPort, e.Message);
Console.WriteLine(text);
Logger.WriteToLog(text);
Console.ForegroundColor = baseColor;
}
Console.Title = string.Format("Server initailised under {0}:{1}",localMachineIP.ToString(),serverPort);
}
public static IPAddress GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip;
}
}
return null;
}
I want to create a windows service from this code. Anyone can help for creating a windows service. I tried many time myself but i get success 50%. In my code i had 3 function that i want to perform after connecting with client application.
public static class Program
{
public static TcpClient client;
private static TcpListener listener;
private static string ipString;
static void Main(string[] args)
{
IPAddress[] localIp = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress address in localIp)
{
if (address.AddressFamily == AddressFamily.InterNetwork)
{
ipString = address.ToString();
}
}
IPEndPoint ep = new IPEndPoint(IPAddress.Parse(ipString), 1234);
listener = new TcpListener(ep);
listener.Start();
client = listener.AcceptTcpClient();
while (client.Connected)
{
try
{
const int bytesize = 1024 * 1024;
byte[] buffer = new byte[bytesize];
string x = client.GetStream().Read(buffer, 0, bytesize).ToString();
var data = ASCIIEncoding.ASCII.GetString(buffer);
if (data.ToUpper().Contains("SLP2"))
{
Sleep();
}
else if (data.ToUpper().Contains("SHTD3"))
{
Shutdown();
}
else if (data.ToUpper().Contains("TSC1"))
{
var bitmap = SaveScreenshot();
var stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Bmp);
sendData(stream.ToArray(), client.GetStream());
}
}
catch (Exception exc)
{
client.Dispose();
client.Close();
}
}
}
}
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'm reading a huge byte of around 3824726 bytes. I've tried a lot of functions for reading the whole bytes. It is reading exactly 3816534 bytes and the while loop is going away some where. Remaining 8192 bytes are not being read and also there is no exception. It reads till exactly 3816534 and then when on while loop goes away somewhere. Please some one help and tell what may be the problem here. I have tried a lot but the same thing is happening in different functions.
public static void ReadFully(NetworkStream stream, int initialLength)
{
if (initialLength < 1)
{
initialLength = 32768;
}
byte[] buffer = new byte[initialLength];
int chunk;
try
{
int read = -1;
int totread = 0;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
totread += read;
Console.WriteLine("Toatal Read" + totread);
string filePath = "C:\\Foo.txt";
StreamWriter objWriter;
using (objWriter = File.AppendText(filePath))
{
objWriter.WriteLine(totread);
objWriter.Flush();
objWriter.Close();
}
}
Console.WriteLine("Toatal Read" + totread);
}
catch (Exception ex)
{ throw ex; }
}
Client Side Sending bytes to server
byte[] fileA;
IPAddress ipAd = IPAddress.Parse("IpAddress");
TcpClient client = new TcpClient(ipAd.ToString(), Port);
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader("D:/Users/Public/Pictures/Sample Pictures/06250_2.jpg");
//StreamReader reader = new StreamReader("D:/Users/703132799/Desktop/Foo.txt");
string data = reader.ReadToEnd();
reader.Close();
fileA = System.Text.Encoding.ASCII.GetBytes(data);
int length = 0;
length = fileA.Length;
Console.WriteLine("Sending Buffer Length-" + length);
stream.Write(fileA, 0, fileA.Length);
stream.Flush();
//Thread.Sleep(10000);
Console.ReadLine();
Whole code at server, It is Asynchronous way
static void Main(string[] args)
{
StartServer();
}
private static TcpListener _listener;
public static void StartServer()
{
IPAddress localIPAddress = IPAddress.Parse("IPAddress");
IPEndPoint ipLocal = new IPEndPoint(localIPAddress, Port);
_listener = new TcpListener(ipLocal);
_listener.Start();
WaitForClientConnect();
}
private static void WaitForClientConnect()
{
object obj = new object();
_listener.BeginAcceptTcpClient(new System.AsyncCallback(OnClientConnect), obj);
Console.ReadLine();
}
private static void OnClientConnect(IAsyncResult asyn)
{
try
{
TcpClient clientSocket = default(TcpClient);
clientSocket = _listener.EndAcceptTcpClient(asyn);
HandleClientRequest clientReq = new HandleClientRequest(clientSocket);
clientReq.StartClient();
}
catch (Exception ex)
{
throw ex;
}
WaitForClientConnect();
}
}
public class HandleClientRequest
{
TcpClient _clientSocket;
NetworkStream _networkStream = null;
public HandleClientRequest(TcpClient clientConnected)
{
this._clientSocket = clientConnected;
}
public void StartClient()
{
_networkStream = _clientSocket.GetStream();
WaitForRequest();
}
public void WaitForRequest()
{
byte[] buffer = new byte[_clientSocket.ReceiveBufferSize];
_networkStream.BeginRead(buffer, 0, buffer.Length, ReadCallback, buffer);
}
private void ReadCallback(IAsyncResult result)
{
string sRecMsgAsciiWithHex = string.Empty;
NetworkStream networkStream = _clientSocket.GetStream();
ReadFully(networkStream, 65536);
}
public static void ReadFully(NetworkStream stream, int initialLength)
{
if (initialLength < 1)
{
initialLength = 32768;
}
byte[] buffer = new byte[initialLength];
int chunk;
try
{
int read = -1;
int totread = 0;
using (var fileStream = File.OpenWrite("C:\\Foo.txt"))
{
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
totread += read;
Console.WriteLine("Toatal Read" + totread);
fileStream.Write(buffer, 0, buffer.Length);
//string filePath = "C:\\Foo.txt";
//StreamWriter objWriter;
//using (objWriter = File.AppendText(filePath))
//{
// objWriter.WriteLine(totread);
// objWriter.Flush();
// objWriter.Close();
//}
}
}
Console.WriteLine("Toatal Read" + totread);
}
catch (IOException e)
{ throw; }
}
UPDATE:
You're not closing the connection - simple as that; if you're interested I can post a full code sample.
Put client.Close(); after the stream.Flush() in the end of "Client Side Sending bytes to server" routine.
All the code:
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace ConsoleApplication1 {
class Program {
static void Main(string[] args) {
StartServer();
// test sending
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(IPAddress.Parse("127.0.0.1"), 4000);
// get a file here instead
byte[] longBuffer = new byte[3824726];
byte[] buffer = new byte[4096];
// emulated stream over emulated buffer
using (var stream = new MemoryStream(longBuffer, false)) {
while (true) {
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0) {
break;
}
for (int sendBytes = 0; sendBytes < read; sendBytes += client.Send(buffer, sendBytes, read - sendBytes, SocketFlags.None)) {
}
}
}
// the tricky part ;)
client.Close();
Console.In.ReadLine();
_stop = true;
}
private static TcpListener _listener;
private static volatile bool _stop = false;
private sealed class Client : IDisposable {
public Socket Socket { get; private set; }
public byte[] Buffer { get; private set; }
public FileStream WriteStream { get; private set; }
public Client(Socket socket) {
if (socket == null) {
throw new ArgumentNullException("socket");
}
Socket = socket;
Buffer = new byte[4096];
WriteStream = File.OpenWrite(#"c:\foo" + Guid.NewGuid().ToString("N") + ".txt");
}
public void Close() {
if (Socket != null) {
Socket.Close();
}
if (WriteStream != null) {
WriteStream.Close();
}
}
public void Dispose() {
Close();
}
}
public static void StartServer() {
IPAddress localIPAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint ipLocal = new IPEndPoint(localIPAddress, 4000);
_listener = new TcpListener(ipLocal);
_listener.Start();
_listener.BeginAcceptSocket(BeginAcceptSocketCallback, null);
}
private static void BeginAcceptSocketCallback(IAsyncResult asyn) {
Client client = null;
try {
client = new Client(_listener.EndAcceptSocket(asyn));
client.Socket.BeginReceive(client.Buffer, 0, client.Buffer.Length, SocketFlags.None, BeginReceiveCallback, client);
} catch (ObjectDisposedException e) {
HandleSocketFailure(client, e, "BeginAcceptSocketCallback failure", false);
} catch (SocketException e) {
HandleSocketFailure(client, e, "BeginAcceptSocketCallback failure", false);
} catch (Exception e) {
HandleSocketFailure(client, e, "BeginAcceptSocketCallback failure", true);
}
if (!_stop) {
_listener.BeginAcceptSocket(BeginAcceptSocketCallback, null);
}
}
private static void BeginReceiveCallback(IAsyncResult result) {
var client = (Client)result.AsyncState;
try {
int bytesRead = client.Socket.EndReceive(result);
if (bytesRead > 0) {
client.WriteStream.Write(client.Buffer, 0, bytesRead);
client.Socket.BeginReceive(client.Buffer, 0, client.Buffer.Length, SocketFlags.None, BeginReceiveCallback, client);
} else {
client.Close();
}
} catch (SocketException e) {
HandleSocketFailure(client, e, "BeginReceiveCallback failure", false);
} catch (ObjectDisposedException e) {
HandleSocketFailure(client, e, "BeginReceiveCallback failure", false);
} catch (Exception e) {
HandleSocketFailure(client, e, "BeginReceiveCallback failure", true);
}
}
private static void HandleSocketFailure(Client client, Exception exception, string message, bool isFatal) {
// log exception as well at least for isFatal = true
if (client != null) {
client.Close();
}
}
}
}