如何使用线程重新连接套接字

时间:2016-05-04 13:31:08

标签: c# multithreading sockets

我有一个简单的服务器 - 客户端套接字应用程序,用于发送/接收文件。我需要覆盖连接丢失时的情况(我使用TCPView使其崩溃)使用踏板。因此,使用线程是一种必须的情况,我不知道该怎么做。这是我的客户端和服务器端代码。感谢。

客户端:

    public static void StartClient()
    {
        // Data buffer for incoming data.
        byte[] bytes = new byte[1024];
        byte[] msg;
        try
        {
            IPAddress ipAd = IPAddress.Parse("127.0.0.1");
            IPEndPoint remoteEP = new IPEndPoint(ipAd, 1234);
            Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                sender.Connect(remoteEP);
                Console.WriteLine("Client connected to {0}", sender.RemoteEndPoint.ToString());
                Console.WriteLine("Sending file...");
                msg = File.ReadAllBytes(@"C:\TCPIP\test_big.txt");
                byte[] msgLengthBytes = BitConverter.GetBytes(msg.Length-3);
                int msgLength = BitConverter.ToInt32(msgLengthBytes, 0);
                Console.WriteLine("int: {0}", msgLength);
                Console.WriteLine("msgL size: {0}", msgLengthBytes.Length);

                //join arrays
                byte[] result = new byte[msgLengthBytes.Length + msgLength];
                Buffer.BlockCopy(msgLengthBytes, 0, result, 0, msgLengthBytes.Length);
                Buffer.BlockCopy(msg, 3, result, msgLengthBytes.Length, msgLength);

                int bytesSent = sender.Send(result);
                Console.WriteLine("result size: {0}", result.Length);

                sender.Shutdown(SocketShutdown.Both);
                sender.Close();

            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException : {0}", se.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception : {0}", e.ToString());
            }    
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    public static void Main(String[] args)
    {
        StartClient();
    }

Server:

public static void Main(String[] args)
{
    StartListening();
}

public static void StartListening()
{
    byte[] bytes = new Byte[1024];

    while (true)
    {
        Console.WriteLine("Waiting for a connection...");
        Socket handler = SocketInstance().Accept();
        data = null;
        //for the TCP header, get file information
        bytes = new byte[4];
        int bytesReceived = handler.Receive(bytes);

        int Lenght = BitConverter.ToInt32(bytes, 0);
        Console.WriteLine("msg length: " + Lenght);
        int TotalReceivedBytes = 0;

        while (TotalReceivedBytes < Lenght)
        {
            bytes = new byte[1024];
            int bytesRec = handler.Receive(bytes);
            TotalReceivedBytes = TotalReceivedBytes + bytesRec;
            data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
        }
        Console.WriteLine("Bytes received total: " + TotalReceivedBytes);
        File.WriteAllText(outputPath, data);
        Console.WriteLine(File.Exists(outputPath) ? "File received." : "File not received.");
        handler.Shutdown(SocketShutdown.Both);
        handler.Close();
    }
    Console.WriteLine("\nPress ENTER to continue...");
    Console.Read();

}

private static Socket SocketInstance()
{
    IPAddress ipAd = IPAddress.Parse("127.0.0.1");
    IPEndPoint localEndPoint = new IPEndPoint(ipAd, 1234);
    Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    listener.Bind(localEndPoint);
    listener.Listen(10);
    return listener;
}

0 个答案:

没有答案