Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Well, what's the problem then? You have TcpListener and TcpClient in C#. You have a port onto where to listen for what you want and you can send back some data. Let me give you an example and be warned, I'm not a C# expert, I just have some knowledge of it.
- Here we have the server code:
- [PHP]
- namespace Server
- {
- class Program
- {
- const int PORT = 5000;
- const string HOST = "127.0.0.1";
- static void Main(string[] args)
- {
- /*! Listen at the specified host and port number */
- IPAddress hostAddress = IPAddress.Parse(HOST);
- TcpListener listener = new TcpListener(hostAddress, PORT);
- Console.WriteLine("Listening...");
- listener.Start();
- /*! Accept incoming client *//
- TcpClient client = listener.AcceptTcpClient();
- /*! Get the incoming data through a network stream */
- NetworkStream networkStream = client.GetStream();
- byte[] buffer = new byte[client.ReceiveBufferSize];
- /*! Read the data from the network stream */
- int bytesRead = networkStream.Read(buffer, 0, client.ReceiveBufferSize);
- /*! Convert the received data into string and print it out */
- string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
- Console.WriteLine("Received : " + dataReceived);
- /*! Return a response to the client */
- Console.WriteLine("Sending back: " + dataReceived);
- networkStream.Write(buffer, 0, bytesRead);
- client.Close();
- listener.Stop();
- Console.ReadLine();
- }
- }
- }
- [/PHP]
- And we have a client (again in C#) just so you are able get the idea how the transmission of data through network actually works:
- [PHP]
- namespace Client
- {
- class Program
- {
- const int PORT = 5000;
- const string HOST = "127.0.0.1";
- static void Main(string[] args)
- {
- /*! Data to send to the server */
- string message = DateTime.Now.ToString();
- /*! Create a TCPClient object to connect to the host with port*/
- TcpClient client = new TcpClient(HOST, PORT);
- NetworkStream networkStream= client.GetStream();
- byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(message);
- /*! Send the message */
- Console.WriteLine("Sending: " + message);
- networkStream.Write(bytesToSend, 0, bytesToSend.Length);
- //---read back the text---
- byte[] bytesToRead = new byte[client.ReceiveBufferSize];
- int bytesRead = networkStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
- Console.WriteLine("Received: " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
- Console.ReadLine();
- client.Close();
- }
- }
- }
- [/PHP]
- You can learn much more onto how the HTTP servers and listeners work overall at the RFC2616 HTTP/1.1 - https://www.ietf.org/rfc/rfc2616.txt
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement