【问题标题】:Socket communication output issue套接字通信输出问题
【发布时间】:2015-02-18 09:17:03
【问题描述】:

为了习惯使用客户端服务器通信的套接字,这里是我的代码。

   //server partl
        try
        {
            IPAddress ipAd = IPAddress.Parse("127.0.0.1"); //use local m/c IP address, and use the same in the client

            /* Initializes the Listener */
            TcpListener myList = new TcpListener(ipAd, 8020);

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


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

            byte[] b = new byte[100];
            int k = s.Receive(b);
            //Console.WriteLine("Recieved...");

            //Writes to label1
            for (int i = 0; i < k; i++)
                label1.Text = b[i].ToString();



            //ASCII endoing to use ACK.
            ASCIIEncoding asen = new ASCIIEncoding();
            s.Send(asen.GetBytes("The string was recieved by the server."));
            Console.WriteLine("\nSent Acknowledgement");

            /* clean up */
            s.Close();
            myList.Stop();


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


        //Client part

        try
        {
            TcpClient tcpclnt = new TcpClient();
            Console.WriteLine("Connecting.....");

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

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

             //gets the text from textbox
            String str = textBox1.Text;
            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]));


            tcpclnt.Close();

        }

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


    }

我正在使用一种表单在本地主机上进行通信并编写一个 .cs 文件,并希望将文本(来自文本框)从客户端标记部分显示到服务器标记部分的标签。

知道为什么它不显示输出吗?套接字新手!!!

【问题讨论】:

  • 也许它没有显示任何内容,因为您正在丢弃所有错误。

标签: c# sockets client-server ip-address tcplistener


【解决方案1】:

当套接字接收数据而不是循环时,只需使用这个:

if (k > 0)
    label1.Text = Encoding.UTF8.GetString(b);

您还可以使用this 来简单地使用 TcpClient 发送和接收数据,它是套接字的包装器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多