C# 如何使用客户端向服务器发送更多消息



我正在编写一个带有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;
}

}

服务器

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 += "nn" + 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关闭,因为没有继续该过程的时间!我尝试在尝试和进入时放置,但代码崩溃了!帮助将不胜感激,帮助或解决方案是相同的,只需得到答案:)谢谢大家

我使用套接字的知识有限。但是我知道您只能拨打以下电话一次:

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;
    }
}

服务器

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 += "nn" + 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;
    }
}

最新更新