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

时间:2013-12-26 04:37:16

标签: c# sockets tcp-ip

基本上我坚持的是,我希望我的客户端连续发送数据和服务器在发送时从客户端读取,就像当我发送“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);
            }    

        }
    }
}

任何帮助将不胜感激

谢谢:)

2 个答案:

答案 0 :(得分:0)

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

服务器端示例:

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

答案 1 :(得分:0)

忽略我之前的回答

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

Console.ReadLine();

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

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

同样如前一张海报所示,如果您希望多个客户端同时连接到此服务器,请将其设置为基于线程。