Aido
Aido

Reputation: 55

C# TCP Client to Server messages

I wrote a C# TCP Server that runs on my desktop, while I have a client running on my windows phone. It works great, the client can connect to the server. But I am trying to make it so the server can receive messages from the client. When I run it, the server just receives a number when I am sending a string. Here is my server code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace TCPServer
{
    class Server
    {
        private TcpListener tcpListener;
        private Thread listenThread;

        public Server()
        {
            this.tcpListener = new TcpListener(IPAddress.Any, 80);
            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();
            Console.WriteLine("Got connection");
            StreamReader clientStreamReader = new StreamReader(clientStream);
            Console.WriteLine(clientStreamReader.Read());
        }

    }
}

Here is the client code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace NetworkingTesting
{
    class Client
    {
        Socket socket = null;
        static ManualResetEvent clientDone = new ManualResetEvent(false);
        const int TIMEOUT_MILLISECONDS = 5000;
        const int MAX_BUFFER_SIZE = 2048;
        DnsEndPoint hostEntry;

        public string Connect(string hostName, int portNumber)
        {
            string result = string.Empty;
            hostEntry = new DnsEndPoint(hostName, portNumber);
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
            socketEventArg.RemoteEndPoint = hostEntry;

            socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
            {
                result = e.SocketError.ToString();
                clientDone.Set();
            });

            clientDone.Reset();
            socket.ConnectAsync(socketEventArg);
            clientDone.WaitOne(TIMEOUT_MILLISECONDS);

            return result;
        }

        public void SendToServer(string message)
        {
            SocketAsyncEventArgs asyncEvent = new SocketAsyncEventArgs { RemoteEndPoint = hostEntry};

            Byte[] buffer = Encoding.UTF8.GetBytes(message + Environment.NewLine);
            asyncEvent.SetBuffer(buffer, 0, buffer.Length);

            socket.SendAsync(asyncEvent);
        }
    }
}

In my main client class, I have: client.SendToServer("hello!"); When I run the server and run the client the server detects the client but receives "104" instead of "Hello". Could anybody explain why this is happening and maybe provide a solution to the problem?

Upvotes: 3

Views: 1884

Answers (1)

Perfect28
Perfect28

Reputation: 11317

When you're doing clientStreamReader.Read() you're just reading one char as int from the stream. Check the doc here. That's why you get only a number.

You need a delimeter to each message to know where it ends, \r\n is often used. Here a sample to make your server receive your hello! String :

In your client Code

client.SendToServer("hello!" + "\r\n");

In your server Code

Console.WriteLine(clientStreamReader.ReadLine()); // Which should print hello!

Upvotes: 2

Related Questions