How to add multiple clients to a server in c#? - c#

My Client Source Code :
public partial class Form1 : Form
{
string serverip = "localHost";
int port = 160;
public Form1()
{
InitializeComponent();
}
private void Submit_Click(object sender, EventArgs e)
{
TcpClient client = new TcpClient(serverip, port);
int byteCount = Encoding.ASCII.GetByteCount(Message.Text);
byte[] sendData = new byte[byteCount];
sendData = Encoding.ASCII.GetBytes(Message.Text);
NetworkStream stream = client.GetStream();
stream.Write(sendData, 0, sendData.Length);
stream.Close();
client.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
My server
class Program
{
static void Main(string[] args)
{
IPAddress ip = Dns.GetHostEntry("localHost").AddressList[0];
TcpListener server = new TcpListener(ip, 160);
TcpClient client = default(TcpClient);
try
{
server.Start();
Console.WriteLine("The server has started successfully");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
while (true)
{
client = server.AcceptTcpClient();
byte[] receivedBuffer = new byte[100];
NetworkStream stream = client.GetStream();
stream.Read(receivedBuffer, 0, receivedBuffer.Length);
StringBuilder msg = new StringBuilder();
foreach (byte b in receivedBuffer)
{
if (b.Equals(59))
{
break;
}
else
{
msg.Append(Convert.ToChar(b).ToString());
}
}
Console.WriteLine(msg.ToString() + msg.Length);
}
}
}
Essentially i want make it so i can have multiple clients on the server sending a message from different ip addresses of course. I have been using c# a year now mostly in school and I am above average at best at it.
First time asking question so sorry if its in wrong format

Related

Receiving data all the time

so made client-server-client tcp/ip app in c# that are supposed to communicate between 2 computers that are in different network.
I have few problems , first of them my server wont start on my public ip sayings its not valid in this context. Second is that I need to press send button twice before it sends data to server ,and then server 2 variations of data, one in bytes, other in char how its supposed to be. And third is how to make clients trying to receive data whole time. Should I have connection between clients have open whole time? I tried using timers to check if there is data to be received from the server.
Server code
static void Main(string[] args)
{
TcpListener server = new TcpListener(IPAddress.Parse("192.168.0.13"), 8080);
TcpClient client = default(TcpClient);
TcpClient client2 = default(TcpClient)
try
{
server.Start();
Console.WriteLine("Server started...");
}
catch(Exception ex)
{
Console.WriteLine("Server failed to start... {0}",ex.ToString());
Console.Read();
}
while (true)
{
client = server.AcceptTcpClient(); /
byte[] receivedBuffer = new byte[1000];
NetworkStream stream = client.GetStream();
stream.Read(receivedBuffer,0,receivedBuffer.Length);
StringBuilder message = new StringBuilder(); foreach (byte b in receivedBuffer)
{
if (b.Equals(126)
) //proveramo d {
break;
}
else
{
message.Append(Convert.ToChar(b).ToString()); }
}
client2 = server.AcceptTcpClient();
byte[] receivedBuffer2 = new byte[1000];
NetworkStream stream2 = client2.GetStream();
stream2.Read(receivedBuffer2, 0, receivedBuffer2.Length);
StringBuilder message2 = new StringBuilder();
foreach (byte g in receivedBuffer2)
{
if (g.Equals(126))
{
break;
}
else
{
message2.Append(g);
}
}
stream2.Write(receivedBuffer, 0, receivedBuffer.Length);
stream.Write(receivedBuffer2,0,receivedBuffer2.Length);
Console.WriteLine(message2.ToString());
Console.WriteLine(message.ToString());
}
Client code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Start();
}
private int port = 8080;
private void submit_Click(object sender, EventArgs e)
{
TcpClient client = new TcpClient("192.168.0.13",port);
TcpListener listener = new TcpListener(IPAddress.Parse("192.168.0.13"), port);
long byteCount = Encoding.ASCII.GetByteCount(messagebox_TB.Text + 1); byte[] sentDataBytes = new byte[byteCount];
sentDataBytes = Encoding.ASCII.GetBytes(messagebox_TB.Text + "~");
NetworkStream stream = client.GetStream();
stream.Write(sentDataBytes,0,sentDataBytes.Length);
stream.Close();
client.Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
long a = 0;
try
{
TcpClient client = new TcpClient("192.168.0.13", port);
TcpListener listener = new TcpListener(IPAddress.Parse("192.168.0.13"), port);
NetworkStream stream = client.GetStream();
byte[] receviedBytes = new byte[100];
stream.Read(receviedBytes, 0, receviedBytes.Length);
StringBuilder
message = new StringBuilder();
foreach (byte b in receviedBytes) {
if (b.Equals(126)
) //proveramo {
break;
}
else
{
message.Append(Convert.ToChar(b).ToString()); }
}
textBox1.Text = message.ToString();
client.Close();
stream.Close();
}
catch
{
a++;
}
}
}

Why is my ReceivedBufferSize huge? Up to 65535 bytes

So I am playing around with the Tcp protocol in C# and figured I would connect to my server.
When I connect to my server it notifies me just fine. but then I go to check the ReceivedBufferSize and it's this receivedBuffer={byte[65536]}
When in reality it only gives back a few bytes.
Why is this happening?
Sending this back to my client doesn't do anything either so I removed that part.
I figured it's because the packet is so big.
This part right here
byte[] receivedBuffer = new byte[client.ReceiveBufferSize];
returns receivedBuffer={byte[65536]}
public partial class MainWindow : Window
{
public static IPAddress remoteAddress = IPAddress.Parse("127.0.0.1");
public TcpListener remoteServer = new TcpListener(remoteAddress, 7777);
public TcpClient client = default(TcpClient);
public MainWindow()
{
InitializeComponent();
}
private void BtnListen_OnClick(object sender, RoutedEventArgs e)
{
if (StartServer())
{
client = remoteServer.AcceptTcpClient();
MessageBox.Show("Connected");
byte[] receivedBuffer = new byte[client.ReceiveBufferSize];
NetworkStream clientStream = client.GetStream();
while (client.Connected)
{
if (client.Connected)
{
if (client.ReceiveBufferSize > 0)
{
receivedBuffer = new byte[100];
clientStream.Read(receivedBuffer, 0, receivedBuffer.Length);
}
}
}
}
}
private bool StartServer()
{
try
{
remoteServer.Start();
MessageBox.Show("Server Started...");
return true;
}
catch (Exception exception)
{
MessageBox.Show(exception.ToString());
throw;
}
}
}
As you can see here, it's only 15 bytes

C# TCP Application won't work

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.

send a hello message from android client to c# server

I'm trying to create this simple client-server. I have an android client and c#server. just a simple program that sends a hello message to the server but the message isn't sent.
my java code:
Thread t= new Thread()
{
#Override
public void run() {
// TODO Auto-generated method stub
try {
Socket myClient= new Socket("192.167.01.123",7000);
DataOutputStream dos= new DataOutputStream(myClient.getOutputStream());
dos.writeBytes("Hello");
dos.flush();
dos.close();
myClient.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
System.out.println("unknown host");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("IOExxception");
}
}
};
t.start();
Toast.makeText(this," Message sent" , Toast.LENGTH_SHORT).show();
}
and c# code:
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(7000);
TcpClient clientSocket = new TcpClient();
serverSocket.Start();
Console.WriteLine("Server started.");
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine("Accept conns from client.");
while (true)
{
try
{
NetworkStream networkStream = clientSocket.GetStream();
Byte[] bytes = new Byte[10025];
networkStream.Read(bytes, 0, (int)clientSocket.ReceiveBufferSize);
string dataClient = System.Text.Encoding.ASCII.GetString(bytes);
Console.WriteLine("data from client: " + dataClient);
networkStream.Flush();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
clientSocket.Close();
serverSocket.Stop();
Console.WriteLine("EXIT");
Console.ReadKey();
}
}
}
Should be inside the while loop
clientSocket = serverSocket.AcceptTcpClient();
Try this:
c# Server Class to Receive Message :
class Server
{
int BUFSIZE = 100;
int servPort = 1551;
public static String ClientOrder = "";
public static int bytesRcvd;
public void RunServer()
{
TcpListener listener = null;
TcpClient client = null;
NetworkStream netStream = null;
listener = new TcpListener(IPAddress.Any, servPort);
listener.Start();
byte[] rcvBuffer = new byte[BUFSIZE];
while (true)
{
client = listener.AcceptTcpClient(); // Get clien
netStream = client.GetStream();
{
rcvBuffer = new byte[BUFSIZE];
bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length);
ClientOrder = (Encoding.ASCII.GetString(rcvBuffer)).Substring(0, bytesRcvd);
netStream.Close();
client.Close();
}
}
}
}
Android Client Class to Send Message:
public class Send_Message_To_Server implements Runnable {
private String mMsg,Server;
private Socket client;
private PrintWriter printwriter;
public Send_Order_To_Server(String msg,String IP) {
mMsg = msg;
Server=IP;
}
public void run() {
try {
client = new Socket(Server, 1551); //connect to server
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(mMsg); //write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); //closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

send data to any connected client

I have created server application to accept connection from clients. After client connected to server ... they can send data and receive data between each other , but when another client is connected ... the server can not send data to frist client connected .
I need help how to save connected client on this server ... and how to send data to specified client.
The server class is :
namespace WindowsApplication11
{
public partial class Form1 : Form
{
private TcpListener tcpListener;
private Thread listenThread;
public Form1()
{
InitializeComponent();
}
TcpListener myList;
private void Form1_Load(object sender, EventArgs e)
{
try
{
myList = new TcpListener(IPAddress.Any, 8001);
/* Start Listeneting at the specified port */
myList.Start();
while (true)
{
TcpClient client = myList.AcceptTcpClient();
saveclient(" Client " + client.Client.RemoteEndPoint.ToString());
// - receive msg from client -
byte[] bb = new byte[10000];
int kb = client.Client.Receive(bb);
string stringu = "";
for (int i = 0; i < kb; i++)
stringu += Convert.ToChar(bb[i]);
// - send msg to accepted client -
Byte[] datat = System.Text.Encoding.ASCII.GetBytes("nje-> " + stringu);
NetworkStream stream = client.GetStream();
stream.Write(datat, 0, datat.Length);
stream.Flush();
}
}
catch (Exception ea)
{
Console.WriteLine("Error..... " + ea.Message);
}
}
void saveclient(string idlidhje)
{
try
{
System.IO.StreamWriter stw = System.IO.File.AppendText("d:\\clients.txt");
string teksti = System.String.Format("{0:G}: {1}.", System.DateTime.Now, idlidhje);
stw.WriteLine(teksti + "\n");
stw.Close();
}
catch (Exception eks)
{
}
}
}
}
The client class is :
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
IPAddress addr = IPAddress.Any;
byte[] data = new byte[1024];
string input, stringData;
TcpClient server;
try
{
server = new TcpClient("127.0.0.1", 8001);
// - send msg -
Byte[] datat = System.Text.Encoding.ASCII.GetBytes("Hello");
NetworkStream stream = server.GetStream();
stream.Write(datat, 0, datat.Length);
stream.Flush();
// - receive msg -
byte[] bb = new byte[10000];
int kb = server.Client.Receive(bb);
string stringu = "";
for (int i = 0; i < kb; i++)
stringu += Convert.ToChar(bb[i]);
}
catch (SocketException fd)
{
MessageBox.Show("Cannot connect " + fd.Message.ToString());
}
}
Robert answered to a similar question here on SO:
https://stackoverflow.com/a/15878306/17646
Basically you have to keep the connected clients in a list (your TcpClient object 'client' gets lost every time the while loop starts again) and you need threads or async methods to handle the different clients.

Categories