簡體   English   中英

C#如何通過客戶端向服務器發送更多消息?

[英]C# How to do to send more message to Server with 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;
}

}

服務器

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

}

現在,如果您復制粘貼此代碼並執行Server,然后執行Client,則可以將某些內容寫入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 += "\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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM