一个连接后C#tcplistener被强制关闭

时间:2018-08-17 17:45:19

标签: c# tcp server client

Tcplistener抛出“ System.IO.IOException:'无法从传输连接中读取数据:现有连接已被远程主机强行关闭。”字节发送一次后,Inner异常也是如此。

我打算创建tcp客户端和服务器,以便服务器不断接收字节并在每次将新字节从客户端发送到端口时运行。客户端执行一次后,它将强制关闭并引发IO异常。

这是客户端代码:

public class Client
{

    private TcpClient tcpClient;

    public void Initialize(string ip, int port)
    {
        try
        {
            tcpClient = new TcpClient(ip, port);

            if (tcpClient.Connected)
                Console.WriteLine("Connected to: {0}:{1}", ip, port);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Initialize(ip, port);
        }
    }

    public void BeginRead()
    {
        var buffer = new byte[256];
        var ns = tcpClient.GetStream();
        ns.BeginRead(buffer, 0, buffer.Length, EndRead, buffer);
    }

    public void EndRead(IAsyncResult result)
    {
        var buffer = (byte[])result.AsyncState;
        var ns = tcpClient.GetStream();
        var bytesAvailable = ns.EndRead(result);

        Console.WriteLine(Encoding.ASCII.GetString(buffer, 0, bytesAvailable));
        BeginRead();
    }

    public void BeginSend(string send)
    {
        //while (true)
        //{
            var bytes = Encoding.ASCII.GetBytes(send);
            var ns = tcpClient.GetStream();
            ns.BeginWrite(bytes, 0, bytes.Length, EndSend, bytes);
        //}
    }

    public void EndSend(IAsyncResult result)
    {

            var bytes = (byte[])result.AsyncState;
            Console.WriteLine("Sending  {0} bytes to server.", bytes.Length);
            Console.WriteLine("Sent: {0}", Encoding.ASCII.GetString(bytes));

    }




    static void Main(string[] args)
    {

            var client = new Client();
            client.Initialize("127.0.0.1", 6969);

            client.BeginRead();
            client.BeginSend("Bytes being sent to the server");

            Console.ReadLine();

    }

}

服务器代码:

class MyTcpListener
{
    public static void Main()
    {
        TcpListener server = null;
        try
        {

            Int32 port = 6969;
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");

            // TcpListener server = new TcpListener(port);
            server = new TcpListener(localAddr, port);



                // Start listening for client requests.
                server.Start();

            // Buffer for reading data
            Byte[] bytes = new Byte[256];
            String data = null;

                // Enter the listening loop.
                while (true)
                {
                    Console.Write("Searching a connection");

                    // Perform a blocking call to accept requests.
                    // You could also user server.AcceptSocket() here.
                    TcpClient client = server.AcceptTcpClient();
                    Console.WriteLine("Connection Established");

                    data = null;


                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int i;


                    // Loop to receive all the data sent by the client.
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        // Translate data bytes to a ASCII string.
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                        Console.WriteLine("Received: {0}", data);

                        // Process the data sent by the client.
                        data = data.ToUpper();

                        byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                        // Send back a response.
                        stream.Write(msg, 0, msg.Length);
                        Console.WriteLine("Sent: {0}", data);
                    }

                    // Shutdown and end connection
                    client.Close();
                }

        }
        catch (SocketException e)
        {
            Console.WriteLine("SocketException: {0}", e);
        }
        finally
        {
            // Stop listening for new clients.
            server.Stop();
        }


        Console.WriteLine("\nHit enter to continue...");
        Console.Read();
    }
}

Visual Studio在以下位置弹出IO异常: while((i = stream.Read(bytes,0,bytes.Length))!= 0)

试图在该语句周围添加try catch,但仍然抛出相同的异常。

0 个答案:

没有答案