sending additional client info to server in C# - c#

I have written a client program using c# socket programming which will send a file to the server. Is there any way I can send a client ID (say: 1234) to the server so that the server can recognize different clients? What modification will I have to make in the following code?
// Client
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
namespace FileTransferClient
{
class Program
{
static void Main(string[] args)
{
try
{
string fileName = #"D:\demo.txt";
string p = Path.GetExtension(fileName);
FileInfo f = new FileInfo(fileName);
long s1 = f.Length;
TcpClient tcpClient = new TcpClient("127.0.0.1", 1234);
Console.WriteLine("Connected. Sending file.");
StreamWriter sWriter = new StreamWriter(tcpClient.GetStream());
byte[] bytes = File.ReadAllBytes(fileName);
sWriter.WriteLine(bytes.Length.ToString());
sWriter.Flush();
sWriter.WriteLine(fileName);
sWriter.Flush();
Console.WriteLine("Sending file");
tcpClient.Client.SendFile(fileName);
}
catch (Exception e)
{
Console.Write(e.Message);
}
Console.Read();
}
}
}

Related

Permanent receiving of sent XML over TCP

C# Form .Net 4.7
A client app should receive XML data from an external payment machine. The XML is automatically sent after each deposit. It's about receiving it at any time and displaying it in a TextBox.
Sending takes place via TCP
The machine opens the connection to the external system at the specified port
Sends the data
Waits for confirmation on the same connection if necessary
Closes the connection
Since the client has to be able to receive the data at any time, I thought about a listener. But I'm not sure if this approach is the right one. What I did here doesn't work. I wanted to test that with a localhost. There is sure to be a simple solution. But since I'm not a network specialist, I can't find it. Does anyone know how to do it best?
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.Xml;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace TCPListener
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
TcpListener Listener = null;
Int32 port = 8080;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
private void button1_Click(object sender, EventArgs e)
{
Listener = new TcpListener(localAddr, port);
byte[] receiveBuffer = new byte[10025];
while (true)
{
int requestCount = 0;
Listener.Start();
MessageBox.Show(" >> Listener Started");
using (var tcpClient = Listener.AcceptTcpClient())
{
MessageBox.Show(" >> Accepted connection from client");
using (var networkStream = tcpClient.GetStream())
{
while (true)
{
try
{
requestCount = requestCount++;
var bytesRead = networkStream.Read(receiveBuffer, 0, (int)tcpClient.ReceiveBufferSize);
if (bytesRead == 0)
{
// Read returns 0 if the client closes the connection
break;
}
string dataFromClient = System.Text.Encoding.ASCII.GetString(receiveBuffer, 0, bytesRead);
XmlDocument xm = new XmlDocument();
xm.LoadXml(string.Format("<root>{0}</root>", dataFromClient));
XmlElement root = xm.DocumentElement;
string rootName = root.FirstChild.Name;
textBox1.Text = (rootName, dataFromClient);
}
catch (Exception ex)
{
MessageBox.Show("ReceivePortMessages: " + ex.ToString());
break;
}
}
}
MessageBox.Show(" >> stopped read loop");
}
Listener.Stop();
}
}
}
}

How to send messages to all clients in multithread chat server?

Sorry for asking about the 'same' thing over and over again. It's yet another edition of the chat. With a lot of searching around I've finally found out how to pass the client list (or at least I hope so) to the Chat function.
However I don't know if this is even supposed to work:
Everytime a client connects :
clients.Add(clientSocket);
var ctThread = new System.Threading.Thread(() => Chat(clients));
where the Chat function hopefully correctly receives the clients via
public void Chat(List<TcpClient> clients)
and then writes this out
foreach (var client in clients)
{
writer.Write(message);
}
With the client having 2 threads (not sure if they can actually read/write at the same time)
Thread ctThread = new Thread(Write);
Thread ctThread2 = new Thread(Read);
ctThread2.Start();
ctThread.Start();
Did I pass the client list to the function properly? and can it actually correctly send the messages? Because right now the server is not responding to anything that I type on the client.
Full code:
Server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.IO;
namespace MultiServeris
{
class Multiserveris
{
static void Main(string[] args)
{
TcpListener ServerSocket = new TcpListener(1000);
ServerSocket.Start();
List<TcpClient> clients = new List<TcpClient>();
Console.WriteLine("Server started.");
while (true)
{
TcpClient clientSocket = ServerSocket.AcceptTcpClient();
handleClient client = new handleClient();
clients.Add(clientSocket);
client.startClient(clientSocket,clients);
}
}
}
public class handleClient
{
TcpClient clientSocket;
public void startClient(TcpClient inClientSocket, List<TcpClient> clients)
{
this.clientSocket = inClientSocket;
var ctThread = new System.Threading.Thread(() => Chat(clients));
}
public void Chat(List<TcpClient> clients)
{
BinaryReader reader = new BinaryReader(clientSocket.GetStream());
BinaryWriter writer = new BinaryWriter(clientSocket.GetStream());
while (true)
{
string message = reader.ReadString();
foreach (var client in clients)
{
writer.Write(message);
}
}
}
}
}
Client
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace Klientas
{
class Klientas
{
public static void Write()
{
while (true)
{
TcpClient clientSocket = new TcpClient("localhost", 1000);
string str = Console.ReadLine();
BinaryWriter writer = new BinaryWriter(clientSocket.GetStream());
writer.Write(str);
}
}
public static void Read()
{
while (true)
{
TcpClient clientSocket = new TcpClient("localhost", 1000);
BinaryReader reader = new BinaryReader(clientSocket.GetStream());
string message = reader.ReadString();
Console.WriteLine(message);
}
}
static void Main(string[] args){
Thread ctThread = new Thread(Write);
Thread ctThread2 = new Thread(Read);
ctThread2.Start();
ctThread.Start();
}
}
}
TCP is not design for broadcasting which is why you're having to loop through all your clients. A better approach would be to use a protocol that supports brodcast use the SignalR Framework or if you want baremetal access use UDP. Here's a great SignalR chat example.
https://dhavalupadhyaya.wordpress.com/tag/signalr-chat-example/

C# Chat clients with multiple threads (read+write at the same time)

How do I make the client read from the stream (for messages of other clients sent to the stream) at the same time as being able to write to them?
I tried creating different threads on the client side (did I even do it right?), however I can still only write to the server, without any response. This is what I'm getting right now:
(Server-Client-Client)
Client:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace Klientas
{
class Klientas
{
public static void Write()
{
while (true)
{
TcpClient clientSocket = new TcpClient("localhost", 1000);
string str = Console.ReadLine();
BinaryWriter writer = new BinaryWriter(clientSocket.GetStream());
writer.Write(str);
}
}
public static void Read()
{
while (true)
{
TcpClient clientSocket = new TcpClient("localhost", 1000);
BinaryReader reader = new BinaryReader(clientSocket.GetStream());
Console.WriteLine(reader.ReadString());
}
}
static void Main(string[] args){
Thread ctThread = new Thread(Write);
Thread ctThread2 = new Thread(Read);
ctThread2.Start();
ctThread.Start();
}
}
}
Server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.IO;
namespace MultiServeris
{
class Multiserveris
{
static void Main(string[] args)
{
TcpListener ServerSocket = new TcpListener(1000);
ServerSocket.Start();
Console.WriteLine("Server started.");
while (true)
{
TcpClient clientSocket = ServerSocket.AcceptTcpClient();
handleClient client = new handleClient();
client.startClient(clientSocket);
}
}
}
public class handleClient
{
TcpClient clientSocket;
public void startClient(TcpClient inClientSocket)
{
this.clientSocket = inClientSocket;
Thread ctThread = new Thread(Chat);
ctThread.Start();
}
private void Chat()
{
while (true)
{
BinaryReader reader = new BinaryReader(clientSocket.GetStream());
Console.WriteLine(reader.ReadString());
}
}
}
}
It seems like you do not have any code on the server to send messages to the client. You need to maintain a list of connected clients and make the server send a message to the eligible clients when it receives a message. Also do not make the client a console app. Unlike most projects for a chat client it is actually harder to do it as a console app.
To keep a list of clients you declare a list of TCP Clients like this
static List<TcpClient> clients = new List<TcpClient>();
Then when a client connects you add it to the list
TcpClient clientSocket = ServerSocket.AcceptTcpClient();
clients.Add(clientSocket);
Then when you receive a message you send it to all clients
BinaryReader reader = new BinaryReader(clientSocket.GetStream());
while(true)
{
string message = reader.ReadString();
foreach(var client in clients)
{
//send message to client
}
}
Now remember that in practice you should handle things like disconnects and adding and removing clients from the list should be thread safe (locks and all).
Good starting point for socket client-server communication: demo application and library. Support for reconnecting, sudden client disconnect catch, message broadcasting and many more.

unable to connect to another computer in C#

hello guyz i have made a bare bone program in C# that simply sends a message from server to client.
Now i have successfully tested both programs running on the same machines. However when i attempt to connect 2 different computers on different networks it sends me the unable to connect message.
Here the server code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Sockets;
namespace chat_client_console
{
class Program
{
static TcpListener listener;
static void Main(string[] args)
{
/*
string name = Dns.GetHostName();
IPAddress[] address = Dns.GetHostAddresses(name);
foreach(IPAddress addr in address)
{
Console.WriteLine(addr);
}
Console.WriteLine(address[2].ToString());*/
Console.WriteLine("server");
listener = new TcpListener(IPAddress.Any, 2055);
listener.Start();
Socket soc = listener.AcceptSocket();
Console.WriteLine("Connection successful");
Stream s = new NetworkStream(soc);
StreamReader sr = new StreamReader(s);
StreamWriter sw = new StreamWriter(s);
sw.AutoFlush = true;
sw.WriteLine("A test message");
sw.WriteLine("\n");
Console.WriteLine("Test message delivered. Now ending the program");
/*
string name = Dns.GetHostName();
Console.WriteLine(name);
//IPHostEntry ip = Dns.GetHostEntry(name);
//Console.WriteLine(ip.AddressList[0].ToString());
IPAddress[] adr=Dns.GetHostAddresses(name);
foreach (IPAddress adress in adr)
{
Console.WriteLine(adress);
}
*/
Console.ReadLine();
}
}
}
and here the client code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Sockets;
namespace chat_client_console_client
{
class Program
{
static void Main(string[] args)
{
string host_ip_address;
Console.WriteLine("Enter server ip address");
host_ip_address=Console.ReadLine();
string display;
TcpClient client = new TcpClient(host_ip_address, 2055);
Stream s = client.GetStream();
Console.WriteLine("Connection successfully received");
StreamWriter sw = new StreamWriter(s);
StreamReader sr = new StreamReader(s);
sw.AutoFlush = true;
/*while (true)
{
display = sr.ReadLine();
if (display == "")
{
Console.WriteLine("breaking stream");
break;
}
}*/
display = sr.ReadLine();
Console.WriteLine(display);
Console.ReadLine();
}
}
}
now when i enter the 127.0.0.1 in the client program it successfully connects to the server and the message is received.
However when i enter my external ip address in the client program running on another computer i am unable to connect.
Suggestions are required in this matter.
Thank you.
You can use Wireshark in the client computer and look up any tcp packet to make sure the message sent to server.

Simple Web Server C#

I need some help with this code:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace HttpEcho
{
class HttpEchoProgram
{
static void Main(string[] args)
{
TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
server.Start();
Console.WriteLine("Waiting for Client...");
TcpClient newConn = server.AcceptTcpClient();
IPEndPoint iep = (IPEndPoint)(newConn.Client.RemoteEndPoint);
IPAddress add = iep.Address;
int prt = iep.Port;
Console.WriteLine("Connected with a client: {0}: {1} ", add, prt);
NetworkStream stream = newConn.GetStream();
StreamReader sr = new StreamReader(stream);
StreamWriter sw = new StreamWriter(stream);
sw.WriteLine("HTTP/1.1 200 OK");
sw.WriteLine("Content-Type: text/plain");
//sw.WriteLine("Content-Length: size");
sw.WriteLine();
String line = null;
while ((line = sr.ReadLine()).Length != 0)
{
Console.WriteLine(line);
sw.WriteLine(line);
sw.Flush();
}
newConn.Close();
server.Stop();
}
}
}
I want to modify this code so it can work as a Simple Web Server that it fetches requested page in the local file system and returns it to the browser.
You can save yourself a few thousand lines of code by starting with a HttpListener instead. http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx

Categories

Resources