Yoda
Yoda

Reputation: 18068

What is the opposite class to TcpListener in C# and how to use it to send message to server

I have programmed TCP Server in my application which can handle incoming connections and decode inoming messages.

But now I wanted create a client on Windows Phone which will send short string message: "I am Client" to the server. In server I used the class TcpListener so I was looking for the "opposite" class like TcpSender but I could not find one.

The servers ip is: 192.168.0.13 and port is 13000.

To sum up the question: How to create short client which will send single message to the server?

My server looks like - I post it only to show that I've done it:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace HomeSecurity {
    class TCPEventServer {
        private TcpListener tcpListener;
        private Thread listenThread;

        public TCPEventServer() {
            this.tcpListener = new TcpListener(IPAddress.Any, 13000);
            this.listenThread = new Thread(new ThreadStart(ListenForClients));
            this.listenThread.Start();
        }
        private void ListenForClients() {
            this.tcpListener.Start();
            while (true) {

                TcpClient client = this.tcpListener.AcceptTcpClient();

                Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                clientThread.Start(client);
            }
        }
        private void HandleClientComm(object client) {
            TcpClient tcpClient = (TcpClient)client;
            NetworkStream clientStream = tcpClient.GetStream();
            byte[] message = new byte[4096];
            int bytesRead;

            while (true) {
                bytesRead = 0;
                try {

                    bytesRead = clientStream.Read(message, 0, 4096);
                } catch {

                    break;
                }
                if (bytesRead == 0) {

                    break;
                }

                ASCIIEncoding encoder = new ASCIIEncoding();

                string messageDecoded = encoder.GetString(message, 0, bytesRead);
                messageDecoded = messageDecoded.Replace("\r", string.Empty).Replace("\n", string.Empty);
                string ip = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address + "";

                Console.WriteLine("message: " + messageDecoded + " ip: " + ip);

                VideoStream.PassMessage(messageDecoded, ip);
            }

            tcpClient.Close();
        }
    }
}

Upvotes: 0

Views: 319

Answers (1)

Craig Graham
Craig Graham

Reputation: 1191

Look at the TcpClient class here. That has functions for establishing a connection to a listener, with example code.

Upvotes: 1

Related Questions