首页 > 解决方案 > 通过 TCPIP 发送字符串和文件的简单方法

问题描述

我想做一个简单的客户端-服务器应用程序。服务器等待来自客户端的连接。客户端可以向服务器发送各种查询(少于 100 个字符的短字符串),服务器应通过发送字符串或文件来响应这些查询。我在网上找到了使用 tcpListener.AcceptSocket() 的代码,我可以发送和接收来自服务器的字符串和使用 tcpListener.AcceptTcpClient() 的代码,我可以将文件发送到不同的服务器程序。下面有一个通过 TcpIP 发送文件的函数和一个通过 TcpIP 发送字符串的函数。服务器代码应该如何适应这两个功能?服务器是一个控制台程序。

    public void SendFileViaTCP(string sFile, string sIPAddress, int portNo)
    {
        byte[] sendingBuffer = null;
        TcpClient client = null;
        toolStripStatusLabel1.Text = "";
        lbConnect.Items.Clear();
        progressBar1.Value = 0;
        Application.DoEvents();
        NetworkStream networkStream = null;
        int bufferSize = 5000;
        string checksum = CalculateMD5(sFile);
        lbConnect.Items.Add("File " + sFile + " checksum = " + checksum);
        try
        {
            client = new TcpClient(sIPAddress, portNo);
            toolStripStatusLabel1.Text = "Connected to the Server...\n";
            networkStream = client.GetStream();
            FileStream fileStream = new FileStream(sFile, FileMode.Open, FileAccess.Read);
            long fsLength = fileStream.Length;
            int nPackets = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(fsLength) / Convert.ToDouble(bufferSize)));
            progressBar1.Maximum = nPackets;
            Application.DoEvents();

            int currentPacketLength;
            for (int i = 0; i < nPackets; i++) {
                if (fsLength > bufferSize) {
                    currentPacketLength = bufferSize;
                    fsLength -= currentPacketLength;
                    Application.DoEvents();
                }
                else {
                    currentPacketLength = Convert.ToInt32(fsLength);
                }

                sendingBuffer = new byte[currentPacketLength];
                fileStream.Read(sendingBuffer, 0, currentPacketLength);
                networkStream.Write(sendingBuffer, 0, (int)sendingBuffer.Length);

                progressBar1.PerformStep();
                Application.DoEvents();
            }

            toolStripStatusLabel1.Text = "Sent " + fileStream.Length.ToString() + " bytes to the server";
            fileStream.Close();
        }
        catch (Exception ex) {
            Console.WriteLine(ex.Message);
        }
        finally {
            networkStream.Close();
            client.Close();
        }
    }

    void SendString(string str, string sIPAddress, int portNo)      
    {
        try {
            TcpClient tcpClient = new TcpClient();
            lbConnect.Items.Add("Connecting...");
            Application.DoEvents();

            // use the ipaddress as in the server program
            var tsk = tcpClient.ConnectAsync(sIPAddress, portNo);
            tsk.Wait(3000);  // here we set how long we want to wait before deciding the server is not responding.            

            lbConnect.Items.Add("Connected");
            lbConnect.Items.Add("Sending string: " + str);
            Application.DoEvents();

            Stream stream = tcpClient.GetStream();

            ASCIIEncoding asen= new ASCIIEncoding();

            byte[] ba=asen.GetBytes(str);
            lbConnect.Items.Add("Transmitting...");
            Application.DoEvents();

            stream.Write(ba,0,ba.Length);

            byte[] bb=new byte[100];
            int k = stream.Read(bb,0,100);

            string sResponse = string.Empty;
            for (int i = 0; i < k; i++) {
                sResponse += Convert.ToChar(bb[i]);
            }

            lbConnect.Items.Add(sResponse);
            Application.DoEvents();

            tcpClient.Close();
        }
        catch (Exception e) {
            lbConnect.Items.Add("Error: " + e.StackTrace);
            Application.DoEvents();
        }
    }

标签: c#winformstcpclientsystem.net

解决方案


推荐阅读