Here is a simple server code written in c# . I want to give a welcome message to the client as soon as it is connected to the server. The welcome message will be displayed on the client's screen. How will I do that?
partial sample code:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
using System.Xml.Serialization;
namespace server
{
class Program
{
static void Main(string[] args)
{
TcpListener tcpListener = new TcpListener(IPAddress.Any, 1234);
tcpListener.Start();
while (true)
{
TcpClient tcpClient = tcpListener.AcceptTcpClient();
byte[] data = new byte[1024];
NetworkStream ns = tcpClient.GetStream();
string[] arr1 = new string[] { "one", "two", "three" };
var serializer = new XmlSerializer(typeof(string[]));
serializer.Serialize(tcpClient.GetStream(), arr1);
int recv = ns.Read(data, 0, data.Length); //getting exception in this line
string id = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(id);
}
}
}
}
what modification is needed to send the welcome message?
May be you can try something like this...
StreamWriter writer = new StreamWriter(tcpClient.GetStream);
writer.Write("Welcome!");
In Client side, you can have below code...
byte[] bb=new byte[100];
TcpClient tcpClient = new TcpClient();
tcpClient.Connect("XXXX",1234) // xxxx is your server ip
StreamReader sr = new StreamReader(tcpClient.GetStream();
sr.Read(bb,0,100);
// to serialize an array and send it to client you can use XmlSerializer
var serializer = new XmlSerializer(typeof(string[]));
serializer.Serialize(tcpClient.GetStream, someArrayOfStrings);
tcpClient.Close(); // Add this line otherwise client will keep waiting for server to respond further and will get stuck.
//to deserialize in client side
byte[] bb=new byte[100];
TcpClient tcpClient = new TcpClient();
tcpClient.Connect("XXXX",1234) // xxxx is your server ip
var serializer = new XmlSerializer(typeof(string[]));
var stringArr = (string[]) serializer.Deserialize(tcpClient.GetStream);
Related
I'm creating a client server app using c# and what it does :
1- the client sends a msg then the server sends it back to the client
2- I want to check what the client send and do some process like if the client send "chrome"
the server checks it and open chrome.exe
I don't know why its not working here on my code:
when the client sends chrome it always shows client disconnected message
also i cant convert it to windows froms app its shows lots of errors
#server code!
using System;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Net;
using System.Text;
namespace consoleTcpServer {
class Program {
class ConnectionHandler {
private Socket client;
private NetworkStream ns;
private StreamReader reader;
private StreamWriter writer;
private static int connections = 0;
//The constructor take the accepted client as argument
public ConnectionHandler(Socket client) {
this.client = client;
}
public void HandleConnection() {
try {
ns = new NetworkStream(client);
reader = new StreamReader(ns);
writer = new StreamWriter(ns);
connections++;
Console.WriteLine("New client accepted: {0} active connections",
connections);
writer.WriteLine("Welcome to my server");
writer.Flush();
string input;
while ((input = reader.ReadLine()).Length != 0) {
if (input.Contains("chrome")) {
System.Diagnostics.Process.Start("chrome.exe", "www.google.com");
} else if (input.Contains("fox")) {
System.Diagnostics.Process.Start("firefox.exe", "www.facebook.com");
}
Console.WriteLine(input);
writer.WriteLine(input);
writer.Flush();
}
// ns.Close();
// client.Close();
connections--;
Console.WriteLine("Client disconnected: {0} active connections", connections);
} catch (Exception) {
connections--;
Console.WriteLine("Client disconnected: {0} active connections",
connections);
}
}
}
static void Main(string[] args) {
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 9050);
server.Bind(localEP);
server.Listen(10);
Console.WriteLine("Waiting for a client");
while (true) {
try {
Socket client = server.Accept();
ConnectionHandler handler = new ConnectionHandler(client);
Thread thread = new Thread(new ThreadStart(handler.HandleConnection));
thread.Start();
} catch (Exception) {
Console.WriteLine("Connection failed ..");
}
//client.Close();
//server.Shutdown();
}
}
}
}
#client code
using System;
using System.Net;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Text;
namespace consoleTcpClient {
class Program {
static void Main(string[] args) {
// Console.WriteLine("Hello World!");
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
client.Connect(remoteEP);
NetworkStream stream = new NetworkStream(client);
StreamReader reader = new StreamReader(stream);
StreamWriter writer = new StreamWriter(stream);
String input = reader.ReadLine();
Console.WriteLine(input);
String line = null;
while (true) {
Console.Write("Enter Message for Server <Enter to Stop >: ");
line = Console.ReadLine();
//writing for server
writer.WriteLine(line);
writer.Flush();
if (line.Length != 0) {
line = "Echo: " + reader.ReadLine();
Console.WriteLine(line);
}
}
// client.Close();
}
}
}
I am trying to program an ident sever to deal with the identity protocol requests from an irc server that I am programming an irc client for. The problem is I try to print to the screen the what I receive but nothing prints. I am not getting an error code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace ConnectIRC
{
class IdentityClass
{
private const int bufSize = 32;
public void IdentityRequest() {
TcpListener listener = null;
int port = 113;
IPEndPoint hostInfo = new IPEndPoint(IPAddress.Any, 113);
listener = new TcpListener(hostInfo);
listener.Start();
byte[] rcvBuffer = new byte[bufSize];
int rec;
for (; ; )
{
TcpClient client = null;
NetworkStream netStream = null;
client = listener.AcceptTcpClient();
if (listener.Pending())
{
Console.WriteLine("Connection was made");
}
netStream = client.GetStream();
//byte[] rcvBuffer = new byte[bufSize];
rec = netStream.Read(rcvBuffer, 0, rcvBuffer.Length);
Array.Resize(ref rcvBuffer, rec);
Console.WriteLine(Encoding.ASCII.GetString(rcvBuffer));
netStream.Close();
client.Close();
}
}
}
}
This is a very basic implementation of an ident server
Obviously it only accepts one connection and closes
Note you'll need to have a port mapped through your router for this to work
public class Ident
{
private readonly TcpListener _listener;
private readonly string _userId;
public Ident(string userId)
{
_userId = userId;
_listener = new TcpListener(IPAddress.Any, 113);
}
public void Start()
{
Console.WriteLine("Ident started");
_listener.Start();
var client = _listener.AcceptTcpClient();
_listener.Stop();
Console.WriteLine("Ident got a connection");
using (var s = client.GetStream())
{
var reader = new StreamReader(s);
var str = reader.ReadLine();
var writer = new StreamWriter(s);
Console.WriteLine("Ident got: " + str + ", sending reply");
writer.WriteLine(str + " : USERID : UNIX : " + _userId);
writer.Flush();
Console.WriteLine("Ident sent reply");
}
Console.WriteLine("Ident server exiting");
}
}
I'm writing a proxy in c# and I wrote this method to get bytes from the stream but after looking at answer in this thread : Proxy won't work in chrome and only partly in firefox I realize that I do not get all the bytes. How can I solve this?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
namespace LexProxy
{
class ProxyServer
{
private TcpListener tcpListener;
public ProxyServer()
{
this.tcpListener = new TcpListener(IPAddress.Any, 3000);
this.tcpListener.Start();
while (true)
{
Console.Write("Waiting for a connection... ");
TcpClient client = tcpListener.AcceptTcpClient();
Thread thread = new Thread(delegate()
{
Serve(client);
});
thread.Start();
}
}
private void Serve(TcpClient client)
{
Console.WriteLine("Connected!");
NetworkStream stream = client.GetStream();
byte[] request = GetBytesFromStream(stream, client.ReceiveBufferSize);
if (request != null)
{
string requestString = System.Text.Encoding.UTF8.GetString(request);
string[] requestParts = requestString.Split(' ');
if (requestParts.Length >= 2)
{
string method = requestParts[0];
if (!requestParts[1].Contains("http://") && !requestParts[1].Contains("https://"))
requestParts[1] = "http://" + requestParts[1];
Uri uri = new Uri(requestParts[1], UriKind.RelativeOrAbsolute);
string host = StringUtils.ReplaceFirst(uri.Host, "www.", "");
int port = uri.Port;
byte[] response = getResponse(host, port, request);
if (response != null)
stream.Write(response, 0, response.Length);
client.Close();
}
}
}
private byte[] getResponse(string host, int port, byte[] request)
{
TcpClient client = new TcpClient(host, port);
NetworkStream stream = client.GetStream();
stream.Write(request, 0, request.Length);
byte[] response = GetBytesFromStream(stream, client.ReceiveBufferSize);
return response;
}
private byte[] GetBytesFromStream(NetworkStream stream, int bufferSize)
{
Byte[] bytes = new Byte[bufferSize];
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
return bytes;
}
return null;
}
}
}
Try out this sample Proxy Server instead:
http://times.imkrisna.com/2011/08/simple-http-proxy-server-c-source-code/
You're doing this wrong. Instead of trying to gather the entire response before sending it downstream, you should just be copying bytes as they arrive. No need to add latency.
But note that the code you have written in getAllBytesFromStream() is nonsense. You have a while loop with an unconditional return statement in it. How is that ever going to execute more than once?
I wanna send data from client to server. There are two queues. in client side and in server side. I want to my client to be connected to the server and send all the data in client queue to the server. In server side I wanna accept all the clients and get all objects and add to the server side queue
Client code :
Queue<Person> clientQueue; // This is the client side queue
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 15884);
var client = new TcpClient();
while(!clientQueue.IsEmpty)
{
Person personObj = clientQueue.Dequeue();
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(clientStream, personObj);
clientStream.Flush();
}
Server Side :
Queue<Person> serverQueue; // This is the server side queue
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 15884);
TcpListener tcpListener = new TcpListener(ipEndPoint);
while(true)
{
TcpClient client = tcpListener.AcceptTcpClient();
NetworkStream clientStream = tcpClient.GetStream();
BinaryFormatter bf = new BinaryFormatter();
Person person = (Person)bf.Deserialize(clientStream);
tcpClient.Close();
serverQueue.Enqueue(person);
}
I know above code is not working. I just wanna sketch my design. Can someone please send me the code example. How to send client queue to server queue..
Thanks..
For the queue at both the server and the client side you should use BlockingCollection if you are using .net 4.0, for earlier versions use a combination of Queue and AutoResetEvent. check this.
At server side you should use asynchronous methods or just instantiate a new thread to handle each new client and then read the data at that thread. like:
TcpClient client = tcpListener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(new WaitHandle(HandleCleint), client);
private void HandleClient(object clientObject)
{
TcpClient client = (TcpClient)clientObject;
NetworkStream clientStream = client.GetStream();
//handle the data here
}
Edit: You stated at a comment:
I don't have an idea about how to change my program to send an entire queue to server side
Array or Queue itself is an object:
//at your client side:
bf.Serialize(clientStream, persons);//assume persons is Queue<Person>
//at your server side:
Queue<Person> persons = (Queue<Person>)bf.Deserialize(clientStream);
Ok. Finally I found the answer for my question doing some investigations/Testings. I ll post it here for someone else.. :)
In my client side first I have to send how much bytes im gonna send to server. and then send that data.. Like this..
Queue<Person> clientQueue; // This is the client side queue
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 15884);
var client = new TcpClient();
NetworkStream clientStream = client.GetStream()
while (disconnectClient)
{
if (clientQueue.Count > 0)
{
Person person = clientQueue.Dequeue();
using (MemoryStream memoryStrem = new MemoryStream())
{
var bf = new BinaryFormatter();
bf.Serialize(memoryStrem, person);
byte[] writeData = memoryStrem.ToArray();
byte[] writeDataLen = BitConverter.GetBytes((Int32)writeData.Length);
clientStream.Write(writeDataLen, 0, 4);
clientStream.Write(writeData, 0, writeData.Length);
}
}
}
clientStream.Dispose();
client.Dispose();
In Server Side :
Queue<Person> serverQueue; // This is the server side queue
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 15884);
TcpListener tcpListener = new TcpListener(ipEndPoint);
tcpListener.Start();
while(true)
{
TcpClient tcpClient = tcpListener.AcceptTcpClient();
NetworkStream clientStream = tcpClient.GetStream();
while (client.Connected)
{
if (client.Available >= 4)
{
try
{
byte[] readDataLen = new byte[4];
clientStream.Read(readDataLen, 0, 4);
Int32 dataLen = BitConverter.ToInt32(readDataLen, 0);
byte[] readData = new byte[dataLen];
clientStream.Read(readData, 0, dataLen);
using (var memoryStream = new MemoryStream())
{
memoryStream.Write(readData, 0, readData.Length);
memoryStream.Position = 0; /// This is very important. It took 4 hrs to identify an error because of this :)
BinaryFormatter bf = new BinaryFormatter();
Person person = (Person)bf.Deserialize(memoryStream);
serverQueue.Enqueue(person);
}
}
catch { }
}
}
tcpClient.Close();
}
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