使用套接字时,输入字符串的格式不正确

时间:2016-12-09 21:03:22

标签: c# sockets

您好我编写了简单的客户端套接字应用程序,其中客户端将一些字符串发送到服务器,服务器接收它并将字符串转换为大写并发送回客户端。客户端将消息从服​​务器打印到控制台。但是当我运行应用程序时,我得到的输入字符串格式不正确'转换从服务器接收的字节时出错。由于我是C#编程的新手,有人可以帮助我理解为什么会出现这个错误,以及如何解决它?

Server.cs

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

namespace Server
{
    public class ServerSocket
    {
        private int port;
        private Socket serverSocket;

        public ServerSocket(int port)
        {
            this.port = port;
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);

            /* Associates a Socket with a local endpoint. */
            serverSocket.Bind(serverEndPoint);

            /*Places a Socket in a listening state.
             * The maximum length of the pending connections queue is 100 
             */
            serverSocket.Listen(100);
        }

        public void start()
        {
            Console.WriteLine("Starting the Server");

            /* Accept Connection Requests */
            Socket accepted = serverSocket.Accept();

            /* Get the size of the send buffer of the Socket. */
            int bufferSize = accepted.SendBufferSize;
            byte[] buffer = new byte[bufferSize];

            /* Receives data from a bound Socket into a receive buffer. It return the number of bytes received. */
            int bytesRead = accepted.Receive(buffer);

            byte[] formatted = new byte[bytesRead];

            for (int i = 0; i < bytesRead; i++)
            {
                formatted[i] = buffer[i];
            }

            String receivedData = Encoding.UTF8.GetString(formatted);
            Console.WriteLine("Received Data " + receivedData);

            String response = receivedData.ToUpper();
            byte[] resp = Encoding.UTF8.GetBytes(response);
            accepted.Send(resp, 0, resp.Length, 0);

            Console.WriteLine("Press some key to close");
            Console.Read();
        }
    }
    class Server
    {
        static void Main(string[] args)
        {
            ServerSocket server = new ServerSocket(1234);
            server.start();
        }
    }
}

Client.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

namespace client
{
    public class ClientSocket{
        private Socket clientSocket;
        private int port;

        public ClientSocket(int port)
        {
            this.port = port;
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }

        public void start()
        {
            Console.WriteLine("Starting client socket");
            try
            {
                IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
                clientSocket.Connect(serverEndPoint);

                Console.WriteLine("Enter some data to send to server");

                String data = Console.ReadLine();

                byte[] bytes = Encoding.UTF8.GetBytes(data);

                clientSocket.Send(bytes);

                Console.WriteLine("Closing connection");

                int receiveBufferSize = clientSocket.ReceiveBufferSize;
                byte[] buffer = new byte[receiveBufferSize];


                int receivedBytes = clientSocket.Receive(buffer);
                byte[] receivedData = new byte[receivedBytes];

                for(int i=0; i < receivedBytes; i++)
                {
                    receivedData[i] = buffer[i];
                    Console.WriteLine(receivedData[i]);
                }

                String received = Encoding.UTF8.GetString(receivedData);

                Console.WriteLine("Response : {}", received);

                Console.WriteLine("Press Enter to close");
                Console.Read();
                clientSocket.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error while connectiong to server {}", e.Message );
            }
        }
    }

    class Client
    {
        static void Main(string[] args)
        {
            ClientSocket clientSocket = new ClientSocket(1234);
            clientSocket.start();

        }
    }
}

1 个答案:

答案 0 :(得分:1)

该行:

Console.WriteLine("Response : {}", received);

应该是:

Console.WriteLine("Response : {0}", received);