【问题标题】:how to send and receive string continously using sockets in c#如何在c#中使用套接字连续发送和接收字符串
【发布时间】:2013-12-27 11:22:03
【问题描述】:

基本上我坚持的是,我希望我的客户端连续发送数据,服务器在发送时从客户端读取,就像我发送“2”时它应该读取“2”并显示等等它应该继续只要我从客户端发送,就可以阅读,只要我按下一些不同的字符,我就可以停止或退出。

我实现的不是连续的,我从客户端 2 发送,服务器接收 2 然后停止,我想连续发送它们,我粘贴在我的代码下方,

client.cs

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

namespace Client
{
    class Program
    {
        const int port = 8001;
        const string ip = "127.0.0.1";
        const int maxBuffer = 100;

        static void Main(string[] args)
        {          
                try
                {
                    while (true)
                    {
                        TcpClient tcpclnt = new TcpClient();
                        Console.WriteLine("Connecting.....");

                        tcpclnt.Connect("127.0.0.1", 8001);
                        // use the ipaddress as in the server program

                        Console.WriteLine("Connected");
                        Console.Write("Enter the string to be transmitted : ");

                        String str = Console.ReadLine();
                        Stream stm = tcpclnt.GetStream();

                        ASCIIEncoding asen = new ASCIIEncoding();
                        byte[] ba = asen.GetBytes(str);
                        Console.WriteLine("Transmitting.....");

                        stm.Write(ba, 0, ba.Length);

                        byte[] bb = new byte[100];
                        int k = stm.Read(bb, 0, 100);

                        for (int i = 0; i < k; i++)
                            Console.Write(Convert.ToChar(bb[i]));
                        Console.ReadLine();
                        tcpclnt.Close();
                    }
                }

                catch (Exception e)
                {
                    Console.WriteLine("Error..... " + e.StackTrace);
                }
            }
    }
}

server.cs

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

namespace Server
{
    class Program
    {
        const int port = 8001;
        const string ip = "127.0.0.1";
        const int maxBuffer = 100;

        static void Main(string[] args)
        {
            try
            {
                IPAddress ipAd = IPAddress.Parse("127.0.0.1");
                // use local m/c IP address, and 
                // use the same in the client
                while (true)
                {
                    /* Initializes the Listener */
                    TcpListener myList = new TcpListener(ipAd, 8001);

                    /* Start Listeneting at the specified port */
                    myList.Start();

                    Console.WriteLine("The server is running at port 8001...");
                    Console.WriteLine("The local End point is  :" +
                                      myList.LocalEndpoint);
                    Console.WriteLine("Waiting for a connection.....");

                    Socket s = myList.AcceptSocket();
                    Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

                    byte[] b = new byte[100];
                    int k = s.Receive(b);
                    Console.WriteLine("Recieved...");
                    for (int i = 0; i < k; i++)
                        Console.Write(Convert.ToChar(b[i]));

                    ASCIIEncoding asen = new ASCIIEncoding();
                    s.Send(asen.GetBytes("The string was recieved by the server."));
                    Console.WriteLine("\nSent Acknowledgement");
                    Console.ReadLine();
                    /* clean up */
                    s.Close();
                    myList.Stop();
                }

            }
            catch (Exception e)
            {
                Console.WriteLine("Error..... " + e.StackTrace);
            }    

        }
    }
}

任何帮助将不胜感激

谢谢:)

【问题讨论】:

  • TCP 是一个,你不能保证什么时候会有任何东西到达,只能保证它,并且在正确的顺序。您应该考虑实现某种应用层协议。

标签: c# sockets tcp-ip


【解决方案1】:

通过使用多线程,您可以在客户端和服务器之间连续发送和接收消息。

服务器端示例:

IPAddress[] ipAdd = Dns.GetHostAddresses("192.168.1.38");
            IPAddress ipAddress = ipAdd[0];
            TcpListener serverSocket = new TcpListener(ipAddress, 8888);
            TcpClient clientSocket = default(TcpClient);
            int counter = 0;
            serverSocket.Start();
            notifyIcon.ShowBalloonTip(5000, "Server Notification", " >> Server Started.", wform.ToolTipIcon.Info);
            counter = 0;
            while (true)
            {
                counter += 1;
                clientSocket = serverSocket.AcceptTcpClient();

                byte[] bytesFrom = new byte[10025];
                string dataFromClient = null;

                NetworkStream networkStream = clientSocket.GetStream();
                networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
                dataFromClient = Encoding.ASCII.GetString(bytesFrom);
                dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
                if (clientsList.ContainsKey(dataFromClient))
                {
                    continue;
                }
                else
                {
                    clientsList.Add(dataFromClient, clientSocket);
                }
                string onlineUsers = "";
                foreach (DictionaryEntry item in clientsList)
                {
                    onlineUsers += item.Key.ToString() + ";";
                }
                onlineUsers =  onlineUsers.Remove(onlineUsers.Length - 1);
                Broadcast.BroadcastSend(dataFromClient + " joined. |" + onlineUsers, dataFromClient, ref clientsList, false, false);

                notifyIcon.ShowBalloonTip(5000,"Client Notification", dataFromClient + " joined.", wform.ToolTipIcon.Info);
                HandleClient client = new HandleClient();
                client.StartClient(clientSocket, dataFromClient, clientsList, notifyIcon);
            }

More details

【讨论】:

    【解决方案2】:

    忽略我之前的回答

    问题是服务器在发送确认后在控制台等待用户响应。

    Console.ReadLine();
    

    只需在原始程序中注释掉这一行即可。

    并通过检查输入添加退出条件。

    也正如之前的海报所建议的,如果您希望多个客户端同时连接到此服务器,请使其基于线程。

    【讨论】:

    • 你好,我做了,但它没有在服务器上打印第二个值,例如,我在服务器上的客户端上按 2,它显示 2,然后我按 Enter,在客户端我按 3,它服务器它不显示任何东西
    • 好的,现在我发现了问题所在。请查看编辑后的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 2011-07-11
    • 2019-10-25
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多