简体   繁体   English

如何在C#中使用套接字连续发送和接收字符串

[英]how to send and receive string continously using sockets in c#

Basically what i am stuck at is , i want my client to send data continously and server to read from client as it sends, like when i send "2" it should read "2" and display and so on it should continue to read as long as i send from the client, i can stop or exit whenever i press some different character,. 基本上,我被困在的是,我希望我的客户端连续发送数据,服务器希望在客户端发送时从客户端读取数据,例如当我发送“ 2”时,它应该读为“ 2”并显示,以此类推,它应该继续读为只要我从客户端发送邮件,只要我按不同的字符,我就可以停止或退出。

what i have acheived is not continous, i send from client 2 and server receives 2 and then it is stopped, i want to send them continously , i am pasting below my code, 我得到的不是连续的,我从客户端2发送,服务器接收2,然后停止,我想连续发送它们,我粘贴在我的代码下面,

client.cs 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 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);
            }    

        }
    }
}

Any help will be appreciated 任何帮助将不胜感激

Thanks :) 谢谢 :)

By using MultiThread you can send and receive message between client and server continuously. 通过使用MultiThread,您可以在客户端和服务器之间连续发送和接收消息。

Server side example: 服务器端示例:

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 更多细节

Ignore my earlier answer 忽略我以前的答案

The problem is that the server is waiting for user response in console after sending acknowledgement. 问题是服务器在发送确认后正在控制台中等待用户响应。

Console.ReadLine();

Just comment out this line in your original program. 只需在原始程序中将此行注释掉即可。

And add a exit condition by checking the input. 并通过检查输入添加退出条件。

Also as the previous poster suggest, make it thread based if you want multiple clients connecting to this server simultaneously. 同样如前一个海报所建议的,如果您希望多个客户端同时连接到该服务器,请使其基于线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM