using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data;namespace socketsend
{
    class SocketCon
    {
        #region [公共定义]
        static int _centerControlPort;
        static IPAddress _centerControlIP;
        static byte[] _sendBuf = new byte[256];
        static SocketCon()
        {
            try
            {
                _centerControlPort = 0;
                _centerControlIP = IPAddress.Parse("127.0.0.1");
            }
            catch (Exception)
            {
                _centerControlPort = 0;
                _centerControlIP = IPAddress.Parse("127.0.0.1");
            }        }
        #endregion        #region [发送字符串类]
        public static int Send(string _strToSend)
        {
            return Send(_centerControlIP, _centerControlPort, _strToSend);
        }        public static int Send(string _remoteIP, int _remotePort, string _strToSend)
        {
            IPAddress _ip = IPAddress.Parse(_remoteIP);
            return Send(_ip, _remotePort, _strToSend);
        }        public static int Send(string _remoteIP, string _remotePort, string _strToSend)
        {
            IPAddress _ip = IPAddress.Parse(_remoteIP);
            int _port = Convert.ToInt32(_remotePort);
            return Send(_ip, _port, _strToSend);
        }        public static int Send(IPAddress _remoteIP, int _remotePort, string _strToSend)
        {            try
            {
                IPEndPoint _remoteHost = new IPEndPoint(_remoteIP, _remotePort);//把ip和端口转化为IPEndpoint实例
                //创建socket
                Socket _localSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //连接到服务器
                _localSocket.Connect(_remoteHost);
                //向服务器发送信息
                //把字符串编码为字节
                byte[] bs = Encoding.Default.GetBytes(_strToSend);
                _localSocket.Send(bs, bs.Length, 0);//发送信息
                _localSocket.Close();
                return 0;
            }
            catch (Exception)
            {
                return -1;
            }
        }
        #endregion        #region [绑定服务器字符串]
        public static int BindSocketText(int _serverPort)
        {
            try
            {
                Socket mySock;
                IPHostEntry _ipEntry = Dns.GetHostEntry(Dns.GetHostName());
                string _computerIP = _ipEntry.AddressList[0].ToString();
                IPAddress _ip = IPAddress.Parse(_computerIP);
                IPEndPoint ipSocket = new IPEndPoint(_ip, _serverPort);
                mySock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                mySock.Bind(ipSocket);
                mySock.Listen(20);
                string filename = @"c:\testfile.exe";
                while (true)
                {
                    Socket tempsocket = mySock.Accept();
                    byte[] buff;
                    int recount;
                    string str = "";                    buff = new byte[1024];
                    recount = tempsocket.Receive(buff);
                    str = Encoding.Default.GetString(buff, 0, recount);
                    str = str.Replace("<", "").Replace(">", "");                    string _clintIp = ((IPEndPoint)tempsocket.RemoteEndPoint).Address.ToString();
                    string ipc = ((IPEndPoint)tempsocket.RemoteEndPoint).Address.ToString();
                    string[] st = str.Split(new Char[] { ',' });                    string cc = st[0].ToString();
                    switch (cc)
                    {
                        //10 c初始化屏的内容
                        case "10":
                            break;                        //叫好弹出窗口显示待诊当前和待诊
                        case "3":
                            ///Thread.Sleep(5000);
                            break;                        //刷新屏幕内容
                        case "33":
                            break;                        //同步时间
                        case "21":
                            break;                        default:
                            if (File.Exists(filename))
                            {
                                File.Delete(filename);
                            }                            //StreamWrite
                            StreamWriter sr = new StreamWriter(File.Create(filename));
                            int result;
                            while (true)
                            {
                                // buff = new Byte[1024];
                                // result = mySock.Receive(buff);  //接收来自绑定的Socket 的数据。
                                sr.Write(Encoding.Default.GetString(buff));
                                //sr.Write();
                                if (recount < 1024)
                                    break;
                            }
                            sr.Close();//close buffer write
                            break;
                    }                }
                // System.Threading.Thread.Sleep(300);
                return 0;
            }
            catch (Exception)
            {
                return -1;
            }
        }        #endregion       

解决方案 »

  1.   

     #region [发送文件类]
            //发送文件
            public static int SendFile(IPAddress _remoteIP, int _remotePort, string _strToSendPath)
            {            try
                {
                    IPEndPoint _remoteHost = new IPEndPoint(_remoteIP, _remotePort);//把ip和端口转化为IPEndpoint实例
                    //创建socket
                    Socket _localSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    //连接到服务器
                    //  _ns = _tc.GetStream(); 
                    _localSocket.Connect(_remoteHost);
                    //读文件
                    string path = "c:\\5.jpg";
                    FileStream fs = new FileStream(path, FileMode.Open);
                    BinaryReader br = new BinaryReader(fs);
                    int sendCount = 0;
                    byte[] countbuffer = null;
                    byte[] clientbuffer = new byte[1004];
                    while (sendCount < fs.Length)
                    {
                        int count = br.Read(_sendBuf, 0, _sendBuf.Length);  //读出要发送的数据
                        countbuffer = BitConverter.GetBytes(count);
                        countbuffer.CopyTo(clientbuffer, 0);
                        _sendBuf.CopyTo(clientbuffer, 4);
                        _localSocket.Send(clientbuffer, 0, 4 + count, SocketFlags.None);
                        System.Threading.Thread.Sleep(10);
                        sendCount += count;
                    }
                    countbuffer = BitConverter.GetBytes(0);
                    countbuffer.CopyTo(clientbuffer, 0);
                    _sendBuf.CopyTo(clientbuffer, 4);
                    _localSocket.Send(clientbuffer, 0, countbuffer.Length, SocketFlags.None);
                    fs.Close();
                    br.Close();
                    _localSocket.Close();
                    return 0;
                }
                catch (Exception)
                {
                    return -1;
                }        }        public static int SendFile(string _remoteIP, string _remotePort, string _strToSendPath)
            {
                IPAddress _ip = IPAddress.Parse(_remoteIP);
                int _port = Convert.ToInt32(_remotePort);
                return SendFile(_ip, _port, _strToSendPath);
            }        #endregion        #region [绑定服务器文件]
            public static int BindSocketFile(int _serverPort)
            {            try
                {
                    Socket mySock;
                    IPHostEntry _ipEntry = Dns.GetHostEntry(Dns.GetHostName());
                    string _computerIP = _ipEntry.AddressList[0].ToString();
                    IPAddress _ip = IPAddress.Parse(_computerIP);
                    IPEndPoint ipSocket = new IPEndPoint(_ip, _serverPort);
                    mySock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    mySock.Bind(ipSocket);
                    mySock.Listen(20);                byte[] _receiveBuf = new byte[1024];
                    Socket tempsocket = mySock.Accept();
                    FileStream fs = new FileStream("c:\\51234.jpg", FileMode.OpenOrCreate);
                    BinaryWriter bw = new BinaryWriter(fs);
                    bool isRead = true;
                    while (isRead)
                    {                    tempsocket.Receive(_receiveBuf, 0, _receiveBuf.Length, SocketFlags.None);
                        int datanum = 0;
                        datanum = BitConverter.ToInt32(_receiveBuf, 0);  //从buffer中的前个字节读出count 
                        if (datanum > 0)                                      //确定每次要接受多少字节数
                        {
                            bw.Write(_receiveBuf, 4, datanum);
                        }
                        else                              //如果接受字节数为就推出
                        {
                            isRead = false;
                        }
                    }                fs.Close();
                    return 0;
                }
                catch (Exception)
                {
                    return -1;
                }
            }        #endregion        #region [发送datatble]        public static int SendDataTable(IPAddress _remoteIP, int _remotePort, byte[] _byteToSend)
            {            try
                {
                    IPEndPoint _remoteHost = new IPEndPoint(_remoteIP, _remotePort);//把ip和端口转化为IPEndpoint实例
                    //创建socket
                    Socket _localSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    //连接到服务器
                    _localSocket.Connect(_remoteHost);
                    //向服务器发送信息
                    //把字符串编码为字节
                    _localSocket.Send(_byteToSend, _byteToSend.Length, 0);//发送信息
                    _localSocket.Close();
                    return 0;
                }
                catch (Exception)
                {
                    return -1;
                }
            }        public static byte[] GetBinaryFormatDatatable(DataTable dt)
            {
                //创建内存流
                MemoryStream memStream = new MemoryStream();
                //产生二进制序列化格式
                IFormatter formatter = new BinaryFormatter();
                //指定DataSet串行化格式是二进制
                dt.RemotingFormat = SerializationFormat.Binary;
                //串行化到内存中
                formatter.Serialize(memStream, dt);
                //将DataSet转化成byte[]
                byte[] binaryResult = memStream.ToArray();
                //清空和释放内存流
                memStream.Close();
                memStream.Dispose();
                return binaryResult;
            }
            #endregion    }
    }