admin 发表于 2022-5-8 09:55:03

clientSocket:实现client的socket通信

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
/*时间:2014-7-12
* 功能:socket发送接收数据,作为服务端
* 问题:发送一次成功,断开连接
*/


namespace ClientSocket
{
    class SocketComm
    {
      NetworkStream stream = null;
      TcpClient tcpClient = null;
      private string ClientIP = "";
      private int ClientPort;
      private Byte[] data = new Byte;//读取的数据
      private Byte[] sData = new Byte;//发送的数据可以发送1024个字节=1Kb,共30Kb
      private Byte[] recBytes = new Byte;//定义缓存区
      private Byte[] recBytes1 = new Byte;//定义缓存区
      private Byte[] stringBytes = new Byte;//定义缓存区
      private Byte[] stopBytes = new Byte;//定义缓存区
      private Byte[] numBytes = new Byte;//定义缓存区
      private int sDataLen = 0;
      private bool sendFile = false;

      public void Start(string ip, int port)
      {
            ClientIP = ip;
            ClientPort = port;
            Thread clientThread = new Thread(Receive);
            clientThread.Start();
            
      }
      public void SendData(byte[] data, int length)
      {
            sData = data;
            sDataLen = length;
      }
      public Byte[] TransferData
      {
            get { return data; }
      }
      public bool SendFile
      {
            get { return sendFile; }
            set
            {
                sendFile = value;
            }
      }
      private void Receive()
      {
            /************************IP地址***********************/
            IPAddress localAddr = IPAddress.Parse(ClientIP);//将IP地址字符串转换为IPAddress实例
            IPEndPoint ipe = new IPEndPoint(localAddr, ClientPort);//服务器主机的IP和Port,创建远程终结点
            /***********************************************/
            Byte[] sendBytes = Encoding.ASCII.GetBytes("Data");
            while (true)
            {
                try
                {
                  /********************发送请求***************************/
                  tcpClient = new TcpClient(ClientIP, ClientPort);
                  stream = tcpClient.GetStream();//创建新实例
                  numBytes = 1;
                  /***********************************************/
                  if (tcpClient.Connected)//连接上
                  {
                        /************************发送接收数据***********************/
                        if(stream.CanWrite)
                        stream.Write(numBytes,0,1);
                        //if (stream.DataAvailable)
                        stream.Read(recBytes, 0, recBytes.Length);
                        Thread.Sleep(100);
                        data = recBytes;
                        if (sendFile)
                        {
                            sendFile = false;
                            stream.Write(sData, 0, sData.Length);
                            Thread.Sleep(100);
                        }
                        char[] charbytes = new char;
                        string fileNameStr = "";
                        //Console.WriteLine("\n接收到数据的前4位:");
                        for (int k = 0; k < 5; k++)//读取文件流中前4位并转成字符串
                        {
                            charbytes = (char)recBytes;
                            fileNameStr += charbytes.ToString();
                            //Console.Write("{0}", (char)charbytes);
                        }
                        if (fileNameStr == "Write")
                        {
                            WriteToFile();
                            for (int i = 0; i < 276; i++)
                              Console.Write("{0}", (char)recBytes);
                            Console.WriteLine("写Config.ini文件数据完毕");
                        }
                  }
                  tcpClient.Close();
                  stream.Close();

                }
                catch (Exception e)
                {
                  Console.WriteLine("SocketException---------------:{0}", e);
                  //client.Close();
                }
            }
      }
      private void delay(int x)
      {
            for (int i = 0; i < x; i++)
            {
                for (int j = 0; j < 100; j++)
                  i++;
            }
      }
      private void WriteToFile()
      {
            FileStream fs = null;
            string currentPath = System.Environment.CurrentDirectory;
            try
            {
                fs = new FileStream(currentPath + @"\\Config.ini", FileMode.Create, FileAccess.Write);//文件流实例化
                BinaryWriter bw = new BinaryWriter(fs);
                byte[] bbytes = new byte;//第5位表示传输文件的长度
                for (int i = 0; i < bbytes.Length; i++)//将bytes[]中的字符强制转成字符串,并且是动态长度
                {
                  bbytes = recBytes;//byte类型转成char类型
                }
                bw.Write(bbytes);//传输的是字节数组型
                bw.Close();
                fs.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("--------------" + e.Message);
            }
      }
    }
}
页: [1]
查看完整版本: clientSocket:实现client的socket通信