C#如何使用客户端向Server发送更多消息?

时间:2017-10-10 22:09:47

标签: c# sockets tcp server client

我正在使用TCP协议编写一个客户端服务器套接字C#来创建“客户端询问,服务器应答”,但是当我执行第一个命令时,我的客户端关闭。我应该放在某个地方,但我不知道在哪里。这是代码:

客户端

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

public class SynchronousSocketClient
{

public static void StartClient()
{
    // Data buffer for incoming data.
    byte[] bytes = new byte[1024];

    // Connect to a remote device.
    try
    {
        // Establish the remote endpoint for the socket.
        // This example uses port 11000 on the local computer.
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

        // Create a TCP/IP  socket.
        Socket sender = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);            
        // Connect the socket to the remote endpoint. Catch any errors.
        try
        {
            sender.Connect(remoteEP);             
            Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());

            Console.WriteLine("Insert text to send to server");
            String a = Console.ReadLine(); //This is a test<EOF>
            // Encode the data string into a byte array.
            byte[] msg = Encoding.ASCII.GetBytes(a);

            // Send the data through the socket.
            int bytesSent = sender.Send(msg);

            // Receive the response from the remote device.
            int bytesRec = sender.Receive(bytes);
            Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));                

            // Release the socket.
            //sender.Shutdown(SocketShutdown.Both);
            //sender.Close();

        }
        catch (ArgumentNullException ane)
        {
            Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
        }
        catch (SocketException se)
        {
            Console.WriteLine("SocketException : {0}", se.ToString());
        }
        catch (Exception e)
        {
            Console.WriteLine("Unexpected exception : {0}", e.ToString());
        }            

    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

public static int Main(String[] args)
{
    StartClient();
    //To avoid Prompt disappear
    Console.Read();
    return 0;
}

}

SERVER

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.IO;
//using System.Diagnostics;

public class SynchronousSocketListener
{

// Incoming data from the client.
public static string data = null;

public static void StartListening()
{
    // Data buffer for incoming data.
    byte[] bytes = new Byte[1024];

    // Establish the local endpoint for the socket.
    // Dns.GetHostName returns the name of the 
    // host running the application.
    IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

    // Create a TCP/IP socket.
    Socket listener = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream, ProtocolType.Tcp);

    // Bind the socket to the local endpoint and 
    // listen for incoming connections.
    try
    {
        listener.Bind(localEndPoint);
        listener.Listen(10);

        byte[] msg = null;
        // Start listening for connections.
        while (true)
        {
            Console.WriteLine("Waiting for a connection...");
            // Program is suspended while waiting for an incoming connection.
            Socket handler = listener.Accept();
            data = null;

            // An incoming connection needs to be processed.
            while (true)
            {


                bytes = new byte[1024];
                int bytesRec = handler.Receive(bytes);
                data += Encoding.ASCII.GetString(bytes, 0, bytesRec);

                if (data.Equals("ping"))
                {
                    // Show the data on the console.                        
                    Console.WriteLine("Text received : {0}", data);

                    // Echo the data back to the client.
                    msg = Encoding.ASCII.GetBytes("pong");
                    handler.Send(msg);
                    break;
                }
                if (data.Equals("dir"))
                {
                    // Show the data on the console.                        
                    Console.WriteLine("Text received : {0}", data);

                    // Echo the data back to the client.
                    msg = Encoding.ASCII.GetBytes(System.AppDomain.CurrentDomain.BaseDirectory);
                    handler.Send(msg);
                    break;                        
                }

                if (data.Equals("files"))
                {
                    // Show the data on the console.                        
                    Console.WriteLine("Text received : {0}", data);

                    String files = "";

                    string[] fileEntries = Directory.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory);
                    foreach (string fileName in fileEntries)
                        files += ProcessFile(fileName);

                    // Echo the data back to the client.
                    msg = Encoding.ASCII.GetBytes(files);
                    handler.Send(msg);
                    break;
                }                    
            }

            // Show the data on the console.
            //Console.WriteLine("Text received : {0}", data);

            // Echo the data back to the client.
            //byte[] msg = Encoding.ASCII.GetBytes(data);

            //handler.Send(msg);
            //handler.Shutdown(SocketShutdown.Both);
            //handler.Close();
        }

    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }

    Console.WriteLine("\nPress ENTER to continue...");
    Console.Read();

}

public static String ProcessFile(string path)
{
    return path += "\n\n" + path;
}

public static void ProcessDirectory(string targetDirectory)
{
    // Process the list of files found in the directory.
    string[] fileEntries = Directory.GetFiles(targetDirectory);
    foreach (string fileName in fileEntries)
        ProcessFile(fileName);

    // Recurse into subdirectories of this directory.
    string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
    foreach (string subdirectory in subdirectoryEntries)
        ProcessDirectory(subdirectory);
}

public static int Main(String[] args)
{
    StartListening();
    return 0;
}

}

现在如果您复制粘贴此代码并执行服务器然后执行客户端,您可以在CLient提示符中写入一些内容并获得答案,但在2尝试CLient关闭时因为没有继续该过程!我尝试放入尝试和进入但代码崩溃!帮助将是一个帮助或解决方案是相同的,只是得到答案:) 谢谢大家

1 个答案:

答案 0 :(得分:0)

我使用套接字的知识有限。但是我知道你应该只调用以下一次:

Socket handler = listener.Accept();

我在上面一行添加了一个while循环,并在if条件结束时删除了break语句。

所以新代码变为:

客户端

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

public class SynchronousSocketClient
{

    public static void StartClient()
    {
        // Data buffer for incoming data.
        byte[] bytes = new byte[1024];

        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            // This example uses port 11000 on the local computer.
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

            // Create a TCP/IP  socket.
            Socket sender = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);
            // Connect the socket to the remote endpoint. Catch any errors.
            try
            {

                    sender.Connect(remoteEP);
                    Console.WriteLine("Socket connected to {0}", sender.RemoteEndPoint.ToString());

                while (true)
                {

                    Console.WriteLine("Insert text to send to server");
                    String a = Console.ReadLine(); //This is a test<EOF>
                                                   // Encode the data string into a byte array.
                    byte[] msg = Encoding.ASCII.GetBytes(a);

                    // Send the data through the socket.
                    int bytesSent = sender.Send(msg);

                    // Receive the response from the remote device.
                    int bytesRec = sender.Receive(bytes);
                    Console.WriteLine("Echoed test = {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));

                }
                // Release the socket.
                //sender.Shutdown(SocketShutdown.Both);
                //sender.Close();

            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException : {0}", se.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception : {0}", e.ToString());
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    public static int Main(String[] args)
    {
        StartClient();
        //To avoid Prompt disappear
        Console.Read();
        return 0;
    }
}

SERVER

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Collections;
using System.IO;
//using System.Diagnostics;

public class SynchronousSocketListener
{
    // Incoming data from the client.
    public static string data = null;

    public static void StartListening()
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Establish the local endpoint for the socket.
        // Dns.GetHostName returns the name of the 
        // host running the application.
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);

        // Bind the socket to the local endpoint and 
        // listen for incoming connections.
        while (true)
        {


            try
            {
                //if (!listener.IsBound)
                //{
                    listener.Bind(localEndPoint);
                //}
                listener.Listen(10);

                byte[] msg = null;
                // Start listening for connections.
                while (true)
                {
                    Console.WriteLine("Waiting for a connection...");
                    // Program is suspended while waiting for an incoming connection.
                    Socket handler = listener.Accept();
                    while (true)
                    {


                        data = null;

                        // An incoming connection needs to be processed.
                        bytes = new byte[1024];
                        int bytesRec = handler.Receive(bytes);
                        data += Encoding.ASCII.GetString(bytes, 0, bytesRec);

                        if (data.Equals("ping"))
                        {
                            // Show the data on the console.                        
                            Console.WriteLine("Text received : {0}", data);

                            // Echo the data back to the client.
                            msg = Encoding.ASCII.GetBytes("pong");
                            handler.Send(msg);
                            //break;
                        }
                        if (data.Equals("dir"))
                        {
                            // Show the data on the console.                        
                            Console.WriteLine("Text received : {0}", data);

                            // Echo the data back to the client.
                            msg = Encoding.ASCII.GetBytes(System.AppDomain.CurrentDomain.BaseDirectory);
                            handler.Send(msg);
                            //break;
                        }

                        if (data.Equals("files"))
                        {
                            // Show the data on the console.                        
                            Console.WriteLine("Text received : {0}", data);

                            String files = "";

                            string[] fileEntries = Directory.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory);
                            foreach (string fileName in fileEntries)
                                files += ProcessFile(fileName);

                            // Echo the data back to the client.
                            msg = Encoding.ASCII.GetBytes(files);
                            handler.Send(msg);
                            //break;

                        }
                    }

                    // Show the data on the console.
                    //Console.WriteLine("Text received : {0}", data);

                    // Echo the data back to the client.
                    //byte[] msg = Encoding.ASCII.GetBytes(data);

                    //handler.Send(msg);
                    //handler.Shutdown(SocketShutdown.Both);
                    //handler.Close();
                }

            }

            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
        Console.WriteLine("\nPress ENTER to continue...");
        Console.Read();

    }

    public static String ProcessFile(string path)
    {
        return path += "\n\n" + path;
    }

    public static void ProcessDirectory(string targetDirectory)
    {
        // Process the list of files found in the directory.
        string[] fileEntries = Directory.GetFiles(targetDirectory);
        foreach (string fileName in fileEntries)
            ProcessFile(fileName);

        // Recurse into subdirectories of this directory.
        string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
        foreach (string subdirectory in subdirectoryEntries)
            ProcessDirectory(subdirectory);
    }

    public static int Main(String[] args)
    {
        StartListening();
        return 0;
    }
}