I am now using the default port number TcpListener serverSocket = new TcpListener(9999);
but because at my client side, i have put a textbox to allow user to manually key in the port number. So how do i make my server side to allow port number from port 1 to 9999 instead
using System;
using System.Threading;
using System.Net.Sockets;
using System.Text;
using System.Collections;
namespace ConsoleApplication1
{
class Program
{
public static Hashtable clientsList = new Hashtable();
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(9999);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
Console.WriteLine("Welcome to NYP Chat Server ");
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 = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
clientsList.Add(dataFromClient, clientSocket);
broadcast(dataFromClient + " Connected ", dataFromClient, false);
Console.WriteLine(dataFromClient + " has join the chat room ");
handleClinet client = new handleClinet();
client.startClient(clientSocket, dataFromClient, clientsList);
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine("exit");
Console.ReadLine();
}
public static void broadcast(string msg, string uName, bool flag)
{
foreach (DictionaryEntry Item in clientsList)
{
TcpClient broadcastSocket;
broadcastSocket = (TcpClient)Item.Value;
NetworkStream broadcastStream = broadcastSocket.GetStream();
Byte[] broadcastBytes = null;
if (flag == true)
{
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg);
}
else
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length);
broadcastStream.Flush();
}
} //end broadcast function
}//end Main class
public class handleClinet
{
TcpClient clientSocket;
string clNo;
Hashtable clientsList;
public void startClient(TcpClient inClientSocket, string clineNo, Hashtable cList)
{
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;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine("From client - " + clNo + " : " + dataFromClient);
rCount = Convert.ToString(requestCount);
Program.broadcast(dataFromClient, clNo, true);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}//end while
}//end doChat
} //end class handleClinet
}//end namespace
Add a setting to your program so that you can change the port...
Project properties -> Settings tab -> create a setting called PortNumber, of type Int32, with a default value of 9999
In your code, retrieve the value with Properties.Settings.Default.PortNumber
EDIT: I misread the question. Do you want to listen to all ports from 1 to 9999 at the same time ?? It doesn't make sense, because
many ports in that range will already be used by other processes
you don't need to listen on so many ports...
If you're worried about having multiple users connected at the same time, that's not an issue : just use a new thread to handle each incoming connection, and call AcceptTcpClient again on the listener on the main thread.
The best option would be to make the port number customizable via the application configuration file.
This would allow the server to change ports without a recompilation.
As far as the code goes, you just need to set the port to use here:
TcpListener serverSocket = new TcpListener(portFromAppConfig);
Also, you shouldn't use ports lower than 1024 - these are reserved ports for system services. You should stick to ports in the higher range of numbers (in general).
You don't normally have a single server listening on multiple ports; it's fairly strange. What you do is accept connections, and then pass them off for processing in another thread, and go back to accepting more connections.
Related
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).
in console application i didn't get error but in windows form application i get an error
i use the same script
CONSOLE APPLICATION SCRIPT:
using System;
using System.Threading;
using System.Net.Sockets;
using System.Text;
using System.Collections;
namespace FASERVERCMD
{
class Program
{
public static Hashtable clientsList = new Hashtable();
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
Console.WriteLine("Chat Server Started ....");
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 = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
clientsList.Add(dataFromClient, clientSocket);
broadcast(dataFromClient + " Joined ", dataFromClient, false);
Console.WriteLine(dataFromClient + " Joined chat room ");
handleClinet client = new handleClinet();
client.startClient(clientSocket, dataFromClient, clientsList);
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine("exit");
Console.ReadLine();
}
public static void broadcast(string msg, string uName, bool flag)
{
foreach (DictionaryEntry Item in clientsList)
{
TcpClient broadcastSocket;
broadcastSocket = (TcpClient)Item.Value;
NetworkStream broadcastStream = broadcastSocket.GetStream();
Byte[] broadcastBytes = null;
if (flag == true)
{
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg);
}
else
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length);
broadcastStream.Flush();
}
} //end broadcast function
}//end Main class
public class handleClinet
{
TcpClient clientSocket;
string clNo;
Hashtable clientsList;
public void startClient(TcpClient inClientSocket, string clineNo, Hashtable cList)
{
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;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine("From client - " + clNo + " : " + dataFromClient);
rCount = Convert.ToString(requestCount);
Program.broadcast(dataFromClient, clNo, true);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}//end while
}//end doChat
}
}
windows form application script :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Collections;
namespace FARATSERVER
{
public partial class Form1 : Form
{
public static Hashtable clientsList = new Hashtable();
public Form1()
{
InitializeComponent();
}
private void btnStartserver_Click(object sender, EventArgs e)
{
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
Console.WriteLine("Chat Server Started ....");
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 = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
clientsList.Add(dataFromClient, clientSocket);
broadcast(dataFromClient + " Joined ", dataFromClient, false);
Console.WriteLine(dataFromClient + " Joined chat room ");
handleClinet client = new handleClinet();
client.startClient(clientSocket, dataFromClient, clientsList);
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine("exit");
Console.ReadLine();
}
public static void broadcast(string msg, string uName, bool flag)
{
foreach (DictionaryEntry Item in clientsList)
{
TcpClient broadcastSocket;
broadcastSocket = (TcpClient)Item.Value;
NetworkStream broadcastStream = broadcastSocket.GetStream();
Byte[] broadcastBytes = null;
if (flag == true)
{
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg);
}
else
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length);
broadcastStream.Flush();
}
}
}
public class handleClinet
{
TcpClient clientSocket;
string clNo;
Hashtable clientsList;
public void startClient(TcpClient inClientSocket, string clineNo, Hashtable cList)
{
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;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine("From client - " + clNo + " : " + dataFromClient);
rCount = Convert.ToString(requestCount);
Program.broadcast(dataFromClient, clNo, true);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}//end while
}//end doChat
}
}
Errors :
Severity Code Description Project File Line Suppression State
Warning CS0618 'TcpListener.TcpListener(int)' is obsolete: 'This
method has been deprecated. Please use TcpListener(IPAddress
localaddr, int port) instead.
http://go.microsoft.com/fwlink/?linkid=14202' FARATSERVER D:\hacks\MVS\FARATSERVER\FARATSERVER\Form1.cs 27 Active
Warning CS0162 Unreachable code
detected FARATSERVER D:\hacks\MVS\FARATSERVER\FARATSERVER\Form1.cs 56 Active
Warning CS0219 The variable 'serverResponse' is assigned but its value
is never
used FARATSERVER D:\hacks\MVS\FARATSERVER\FARATSERVER\Form1.cs 105 Active
Warning CS0219 The variable 'sendBytes' is assigned but its value is
never
used FARATSERVER D:\hacks\MVS\FARATSERVER\FARATSERVER\Form1.cs 104 Active
Error CS0117 'Program' does not contain a definition for
'broadcast' FARATSERVER D:\hacks\MVS\FARATSERVER\FARATSERVER\Form1.cs 121 Active
The broadcast method no longer resides in the Program class. It is now inside the Form1 class, so change the code on line 104 in the Winforms program from:
Program.broadcast(dataFromClient, clNo, true);
to
Form1.broadcast(dataFromClient, clNo, true);
(Code can be found in handleClinet => doChat => while => try)
Update based on advice from Steve:
Your "errors" are mostly warnings but only 1 is an error.
With warnings, your code compiles and works, but the compiler is "warning" you that something you did isn't really correct / should change if possible.
Error's really need to be fixed. So when you posted all your "errors" you actually posted only 1 error and 4 warnings.
I made a chat application (Client + server) with following model:
http://csharp.net-informations.com/communications/csharp-chat-server-programming.htm
The difference is, that i made the client in a console application too. Here's the code of my Client Class:
class Program
{
static TcpClient clientSocket = new TcpClient();
static NetworkStream serverStream = default(NetworkStream);
static string readData = null;
static void Main(string[] args)
{
connect();
while (true)
{
string send = Console.ReadLine();
byte[] outStream = Encoding.ASCII.GetBytes(send + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}
}
private static void connect()
{
readData = "Connected to Chat Server...";
msg();
clientSocket.Connect("localhost", 8888);
serverStream = clientSocket.GetStream();
byte[] outStream = Encoding.ASCII.GetBytes("somerandomusername" + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
Thread ctThread = new Thread(getMessage);
ctThread.Start();
}
private static void getMessage()
{
while (true)
{
serverStream = clientSocket.GetStream();
int buffSize = 0;
byte[] inStream = new byte[10025];
buffSize = clientSocket.ReceiveBufferSize;
serverStream.Read(inStream, 0, buffSize);
string returndata = Encoding.ASCII.GetString(inStream);
if (returndata != null)
{
readData = "" + returndata;
msg();
}
}
}
private static void msg()
{
Console.WriteLine(">> " + readData);
}
}
and here's the code from my Server class:
class Program
{
public static Hashtable clientsList = new Hashtable();
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
Console.WriteLine("Server started...");
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("$"));
clientsList.Add(dataFromClient, clientSocket);
broadcast(dataFromClient + " Joined", dataFromClient, false);
Console.WriteLine(dataFromClient + " Joined chat room");
handleClient client = new handleClient();
client.startClient(clientSocket, dataFromClient, clientsList);
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine("exit");
Console.ReadLine();
}
public static void broadcast(string msg, string uName, bool flag)
{
foreach (DictionaryEntry client in clientsList)
{
TcpClient broadcastSocket;
broadcastSocket = (TcpClient)client.Value;
NetworkStream broadcastStream = broadcastSocket.GetStream();
Byte[] broadcastBytes = null;
if (flag == true)
{
broadcastBytes = Encoding.ASCII.GetBytes(uName + ": " + msg);
}
else
{
broadcastBytes = Encoding.ASCII.GetBytes(msg);
}
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length);
broadcastStream.Flush();
}
}
}
public class handleClient
{
TcpClient clientSocket;
string clNo;
Hashtable clientsList;
public void startClient(TcpClient inClientSocket, string clineNo, Hashtable cList)
{
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;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
Console.WriteLine("From client - " + clNo + " : " + dataFromClient);
rCount = Convert.ToString(requestCount);
Program.broadcast(dataFromClient, clNo, true);
}
catch (Exception ex)
{
clientsList.Remove(clNo);
Console.WriteLine(clNo + " hat den Chat verlassen");
break;
}
}
}
}
Somehow the client displays a lot of empty lines when receiving messages. Here's a screenshot: http://i.stack.imgur.com/CoF5B.png.
above the first red marker there are empty lines. it marks the area where i typed in my message, pressed enter and the server response was written. to see it i would have to scroll down to the red marker. then there are the empty lines. the second red marker marks the area where the next message would appear.
I would be really thankful if you could help me removing this problem.
I see what your problem is here is the fixed code (in the client):
private static void getMessage()
{
while (true)
{
serverStream = clientSocket.GetStream();
int buffSize = 0;
buffSize = clientSocket.Available;
byte[] inStream = new byte[buffSize];
serverStream.Read(inStream, 0, buffSize);
string returndata = Encoding.ASCII.GetString(inStream);
if (returndata != null)
{
readData = "" + returndata;
msg();
}
}
}
You where reading the buffer size into an array you want the available bytes.
David
You are sure you are receiving any text? Are you sending text correctly? Are you getting any errors? Set breakpoints before the broadcast of data and also a breakpoint at the receiving end and check if your variables do contain what you expect they contain.
Is it not that you are trying to read from the Stream which does not have any data and gives you dummydata what results in the application printing new lines with no text because it just has no text to send?
Are the amount of lines of empty text the same as the length of the string you send?
Your problem is the misuse of Encoding.ASCII.GetString:
A byte value of 0 will get converted into space, not into '\0' as you might suspect. And since you initialize it with 10025 zeros you have a bunch of spaces filling up your lines.
Trimming your returndata before appending it to readData will solve this problem but will have side effects like not allowing leading and trailing spaces in your message.
You can try this to understand the problem:
static void Main(string[] args)
{
byte[] lolempty = new byte[1024];
string encoded = Encoding.ASCII.GetString(lolempty);
Console.WriteLine(encoded.Length.ToString());
Console.WriteLine("[{0}]", encoded);
}
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).
Hello I am doing a socket program in C# and now I have got a problem. I use this server program code and this client code that I have been finding. I have ben modifying it some. So the problem I haw is that I do want to be able to disconnect from the server, I have been trying and googling it a lot but can't find out how to do it. What is the easy way to do it with this code??
the client code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
namespace soket_client_delen
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
public Form1()
{
InitializeComponent();
this.textBox2.KeyPress += new System.Windows.Forms.KeyPressEventHandler(CheckKeys);
}
private void CheckKeys(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
if (e.KeyChar == (char)13)
{
// Then Enter key was pressed
if (checkBox1.Checked ==true)
send();
}
}
private void Form1_Load(object sender, EventArgs e)
{
msg("Client Started");
clientSocket.Connect("127.0.0.1", 8888);
label1.Text = "Client Socket Program - Server Connected ...";
}
private void button1_Click_1(object sender, EventArgs e)
{
send();
}
public void send()
{
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text +"$");
textBox2.Text = "";
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
msg("Data from Server : " + returndata);
}
public void msg(string mesg)
{
textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + mesg;
}
private void button2_Click(object sender, EventArgs e)
{
}
}
}
and server code:
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace soket_serverdelen
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
Console.WriteLine(" >> " + "Server Started");
counter = 0;
while (true)
{
counter += 1;
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(" >> " + "Client No:" + Convert.ToString(counter) + " started!");
handleClinet client = new handleClinet();
client.startClient(clientSocket, Convert.ToString(counter));
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine(" >> " + "exit");
Console.ReadLine();
}
}
//Class to handle each client request separatly
public class handleClinet
{
TcpClient clientSocket;
string clNo;
public void startClient(TcpClient inClientSocket, string clineNo)
{
this.clientSocket = inClientSocket;
this.clNo = clineNo;
Thread ctThread = new Thread(doChat);
ctThread.Start();
}
private void doChat()
{
int requestCount = 0;
byte[] bytesFrom = new byte[10025];
string dataFromClient = null;
Byte[] sendBytes = null;
string serverResponse = null;
string rCount = null;
requestCount = 0;
while ((true))
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
rCount = Convert.ToString(requestCount);
serverResponse = "Server to clinet(" + clNo + ") " + rCount;
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
Console.WriteLine(" >> " + serverResponse);
}
catch (Exception ex)
{
Console.WriteLine(" >> " + ex.ToString());
}
}
}
}
}
Thanks you for all help
Did you try clientSocket.Close()?
http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.close.aspx
You need to have both sides calling close. Typically, though not a hard and fast rule, the client terminates the connection and the server side responds to that. So, when your client is done transmitting/receiving, the client side calls close. The server side then responds to that and calls close on its side.
For client side:
NetworkStream ns = clientSocket.GetStream();
// send important stuff
// receive important stuff from server
ns.Close();
For the server side:
NetworkStream ns = clientSocket.GetStream();
int bytesRead;
while((bytesRead = ns.Read(buffer, 0, buffer.Length)) >= 0) {
if(bytesRead > 0) {
// do really important stuff
} else if(bytesRead == 0) {
// client has trasmitted FIN packet, close and exit thread
ns.Close();
} else {
// handle error condition
// probably close the connection
}
}
The above code is a model only. I've not tested it. You're using network streams so this example (I think) should be helpful. I usually use select() (from the windows API, .NET exposes it in the Socket class) for doing this. Basically, when either side closes the connection, via Close(), the Windows TCP stacks send a TCP FIN packet. This signals that the originating side wishes to close the connection. Also, someone commented that you should wrap your use of these streams in a using clause. That's imperative if you're not going to call Close() directly.
Typically the client would send a logoff-signal to the server. Upon receiving this message the server closes the connection. The client should run a loop untill serverStream.Socket.Closed = True before exiting.