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);
}
Related
I have implemented a simple chat program (found here: http://csharp.net-informations.com/communications/csharp-chat-server.htm), and I wish to unit test the function "button1_Click" in my client, but how would I do this? I can't figure out how to test, that the function outputs the coorect stream.
I'm fairly new to the world of unit tests, so any help is appriciated :)
The client is as follows:
using System;
using System.Windows.Forms;
using System.Text;
using System.Net.Sockets ;
using System.Threading;
namespace WindowsApplication2
{
public partial class Form1 : Form
{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
NetworkStream serverStream = default(NetworkStream);
string readData = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}
private void button2_Click(object sender, EventArgs e)
{
readData = "Conected to Chat Server ...";
msg();
clientSocket.Connect("127.0.0.1", 8888);
serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox3.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
Thread ctThread = new Thread(getMessage);
ctThread.Start();
}
private 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 = System.Text.Encoding.ASCII.GetString(inStream);
readData = "" + returndata;
msg();
}
}
private void msg()
{
if (this.InvokeRequired)
this.Invoke(new MethodInvoker(msg));
else
textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + readData;
}
}
}
and the server is as follows:
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(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
} //end class handleClinet
}//end namespace
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'm having communication problems with my Program.cs class and my handleClinet.cs class.. Program handles accepting connection from every new client that attempts connecting, and handleClinet is responsible for handling every client's individual interaction.
I have a while loop in each class which is, i assume, where the problem lies.. but I'm not sure how else to do this. The server responses are not corresponding to what they're supposed to be responding. (i.e. not going into my broadcast function and executing the statements in the Program while loop) does anyone have a solution to this? Thanks in advance
class Program
{
public static Hashtable clientsList = new Hashtable();
static void Main(string[] args)
{
UdpClient server = new UdpClient(8888);
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
string data = "";
Console.WriteLine("Auction Server Started ....");
while (true)
{
try
{
//Reads data
byte[] inStream = server.Receive(ref remoteEndPoint);
data = Encoding.ASCII.GetString(inStream);
Console.WriteLine("REGISTER Client at " + remoteEndPoint);
byte[] sendBytes = Encoding.ASCII.GetBytes("REGISTERED " + remoteEndPoint.ToString());
server.Send(sendBytes, sendBytes.Length, remoteEndPoint);
handleClinet client = new handleClinet();
clientsList.Add(data, server);
client.startClient(server, data, clientsList, remoteEndPoint);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
//break;
}
}
}
//Broadcast method is used to send message to ALL clients
public static void broadcast(UdpClient dest, string msg, string uName, bool flag, IPEndPoint sendEP)
{
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
}
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
{
requestCount = requestCount + 1;
byte[] received = clientSocket.Receive(ref remoteIPEndPoint);
dataFromClient = Encoding.ASCII.GetString(received);
Console.WriteLine(dataFromClient);
rCount = Convert.ToString(requestCount);
if (dataFromClient.Contains("DEREGISTER"))
Program.broadcast(clientSocket, "DREG-CONF", clNo, true, myEP);
else
Program.broadcast(clientSocket, dataFromClient, clNo, true, myEP);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
break;
}
}//end while
}//end doChat
} //end class handleClinet
}
This question already has an answer here:
networkStream.Read is blocking
(1 answer)
Closed 8 years ago.
I'm currently doing an application of chat between a server with a client. It works, but then it can only follow the sequence of starting by [client send to server]->[server send to client again]. If server didn't send it back to client, client will remain freeze. I actually want to make my client able to keep on sending to server without those sequence. Is there any suggestion I can use? Like background worker or what? I tried keypress but it doesn't works well. I will try any suggestion, thanks.
The first code is my server code in console application and the second code is my client code in windows forms application.
namespace TcpIpNewServer
{
class Program
{
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
Console.WriteLine(">> Server started...");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine(">> Accepted connection from client...");
while ((true))
{
NetworkStream networkStream = clientSocket.GetStream();
byte[] bytesFrom = new byte[10025];
networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
if (bytesFrom[0].ToString() != "0") //listen from client
{
string dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$^$~~)(")); //hardcode
Console.WriteLine("<< Client : " + dataFromClient);
}
//var cki = Console.ReadKey(true);
//if (cki.KeyChar == 't')
//{
string serverResponse = Console.ReadLine();
if (serverResponse != null) //write to client
{
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
}
//}
}
}
}
}
Client code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Msg("Client started...");
try
{
clientSocket.Connect("127.0.0.1", 8888);
NetworkStream serverStream = clientSocket.GetStream();
label1.Text = "Client Socket Program - Server connected...";
}
catch (Exception ex)
{
label1.Text = "Client Socket Program - Server connection failed... Please try again...Make sure server is on...";
}
}
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
private void button1_Click(object sender, EventArgs e)
{
NetworkStream serverStream = clientSocket.GetStream();
if (textBox1.Text != "" && textBox1.Text != null) //write to the server
{
//string trimDataText = Regex.Replace(textBox1.Text, #"s", "");
string cloneTextbox = textBox1.Text + "$^$~~)(";
Msg("Me: " + textBox1.Text);
textBox1.Text = "";
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(cloneTextbox);
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
}
byte[] inStream = new byte[10025]; //read from the server
//if (inStream[0].ToString() != "0")
//{
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
Msg2("Server: " + returndata);
//}
}
private void Msg(string mesg)
{
richTextBox1.Text = richTextBox1.Text + Environment.NewLine + ">> " + mesg;
}
private void Msg2(string mesg)
{
richTextBox1.Text = richTextBox1.Text + Environment.NewLine + "<< " + mesg;
}
You'll need to switch to async reading/writing ie. NetworkStream.BeginRead()
http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.beginread%28v=vs.110%29.aspx