Клиент C # не получает сообщение с сервера, не уверен, что случилось - PullRequest
0 голосов
/ 18 февраля 2012

Пожалуйста, скажите мне, что не так. также обратите внимание, что я пытался отладить это, поэтому некоторый код может быть лишним и не нужен, но не должен мешать ему работать. Я знаю, что клиент никогда не получал сообщение, потому что я использовал console.write по обе стороны от него, и только выше показывалось socket.read () Я оставил эти два console.write на этот пост.

Сервер:

class class1
{
    static void Main(string[] args)
    {
                TcpListener serverSocket = new TcpListener(IPAddress.Any, info.Port);
                TcpClient clientSocket = default(TcpClient);
                serverSocket.Start();
                log.write(">> Listening for Clients\n");
                bool running = true;
                while (running)
                {
                  clientSocket = serverSocket.AcceptTcpClient();
                  newClient client = new newClient(clientSocket,log);
                  Thread clientThread = new Thread(new ThreadStart(client.start));
                  clientThread.Start();
            }
    }
}

class Client
{
        private clientType cType;
        private EndPoint cIP;
        private TcpClient socket;
        private NetworkStream cStream;

        public NetworkStream stream { get { return cStream; } }
        public clientType Type
        {
        get
                {
            return cType;
                }
            set
                {
                    cType = value;
                }
        }
        public EndPoint IP
        {
        get
                {
                    return cIP;
        }   
                set
                {
                    cIP = value;
                }
        }

        public Client(TcpClient clientSocket)
        {
                socket = clientSocket;
                cStream = socket.GetStream();

        }
    }

class newClient
{
    Client client;

    public newClient(tcpClient socket)
    {
        client = new Client(socket);
    }

    public void start()
    {
        loginObj loginRequest = new loginObj();
        BinaryFormatter formatter = new BinaryFormatter();
        MemoryStream memory = new MemoryStream();
        formatter.Serialize(memory, loginRequest);
        byte[] tempOutBytes = new byte[10025];
        byte[] outBytes;
        int numOfBytes = memory.read(tempOutBytes,0,tempOutBytes.Length);
        outBytes = new byte[numOfBytes];
        for(int counter = 0; counter < nuOfBytes; counter++)
            outBytes[counter] = tempOutBytes[counter];
        client.stream.Write(outBytes,0,outBytes.Length);
        //Rest of code waits for respond but client never gets the message so rest of code is not needed
    }
}

клиент:

class network
{
    private TcpClient socket = new TcpClient();

    public void start()
    {
        NetworkStream stream = socket.GetStream();
        MemoryStream memory = new MemoryStream();
        BinaryFormatter formatter = new BinaryFormatter();
        byte[] tempInBytes = new byte[10025];
        byte[] inBytes;
        int numOfBytes = stream.Read(tempInBytes,0,tempInBytes.Length);
        inBytes = new byte[numOfBytes];
        for(int counter = 0; counter < numOfBytes; counter++)
            inBytes[counter] = tempInBytes[counter];
        memory.write(inBytes,0,inBytes.Length);
        object msgObj = formatter.Deserialize(memory);
        Type msgType = msgObj.GetType();

        if(msgType == typeof(loginObj))
        {
            console.write("It works");
        }
    }
}

1 Ответ

1 голос
/ 18 февраля 2012

Серверная программа

    using System;
    using System.Net.Sockets;
    using System.IO;
    using System.Threading;

    namespace Server
    {
        class Program
        {
            static void Main(string[] args)
            {
                TcpListener server = new TcpListener(5000);
                server.Start();
                Console.WriteLine("Server Started at {0}",DateTime.Now.ToString());
                while (true)
                {
                    Socket client = server.AcceptSocket();
                    Thread th = new Thread(ProcessSocket);
                    th.Start(client);
                }

            }
            public static void ProcessSocket(object o)
            {
                Socket client = (Socket)o;
                NetworkStream nws = new NetworkStream(client);
                StreamReader sr = new StreamReader(nws);
                while(client.Connected)
                {
                    string s = sr.ReadLine();
                    Console.WriteLine(" Message from {0} is :{1}", client.LocalEndPoint.ToString(), s);
                }
            }
        }
    }

Клиентская программа

using System;
using System.Net.Sockets;
using System.IO;


namespace Client
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpClient  client = new TcpClient();
            client.Connect("IP/Hostname", 5000);
            NetworkStream nws = new NetworkStream(client.Client);
            StreamWriter sw = new StreamWriter(nws);
            while (client.Connected)
            {
                Console.Write("your Message:");
                string s=Console.ReadLine();
                sw.WriteLine(s);
                sw.Flush();
                Console.WriteLine("Message sent to server");
            }

        }
    }
}
...