首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C#如何通过客户端向服务器发送更多消息?

C#如何通过客户端向服务器发送更多消息?
EN

Stack Overflow用户
提问于 2017-10-11 06:09:47
回答 1查看 814关注 0票数 1

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

客户端

代码语言:javascript
复制
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;
}

}

服务器

代码语言:javascript
复制
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关闭,因为没有时间继续该过程!我尝试了put while out of try and into,但是代码崩溃了!帮助表示感谢帮助或解决方案是相同的,只要得到一个答案:)谢谢大家

EN

回答 1

Stack Overflow用户

发布于 2017-10-11 08:16:04

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

代码语言:javascript
复制
Socket handler = listener.Accept();

我在上面的代码行下面添加了一个while循环,并在if条件的末尾删除了break语句。

因此,新代码变成:

客户端

代码语言:javascript
复制
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;
    }
}

服务器

代码语言:javascript
复制
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;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46676804

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档