Exemplo n.º 1
0
        static void Main(string[] args)
        {
            Config.LoadConfig();

            string name = Dns.GetHostName();

            IPAddress host = Dns.GetHostAddresses(Dns.GetHostName()).Where(ip =>
                                                                           ip.AddressFamily == AddressFamily.InterNetwork && !ip.ToString().StartsWith("172")).FirstOrDefault();

            Display.WriteLine(string.Format("Working as server ...\nIP address: {0}\nPort num: {1}", host.ToString(), Config.ServerPort.ToString()));


            SocketServer s;

            s = new SocketServer(host, Config.ServerPort);
            try
            {
                //s.InitializeServer();
                // 绑定端口,启动listen
                IPEndPoint ipe = new IPEndPoint(host, Config.ServerPort);
                s.server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                s.server.Bind(ipe);
                //s.server.SendTimeout = 3000;
                //s.server.ReceiveTimeout = 3000;
                s.server.Listen(20);
                Display.WriteLine("Server initiated.");
                // 从主线程创建监听线程
                //s.StartListen();
                Thread th_listen = new Thread(s.ServerListen);
                th_listen.IsBackground = true;
                th_listen.Start();
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                s.Close();
                Display.WriteLine("Server window start listening error: " + ex.Message);
            }
            Console.ReadLine();
        }
Exemplo n.º 2
0
 public void ServerListen()
 {
     try
     {
         while (flag_listen)
         {
             // 等待client连接时, 代码阻塞在此
             Socket client = server.Accept();
             // 可以在这里通过字典记录所有已连接socket
             // 参考 https://www.cnblogs.com/kellen451/p/7127670.html
             //Display.TimeWriteLine("client connected");
             Thread th_receive = new Thread(ReceiveData);
             th_receive.IsBackground = true;
             th_receive.Start(client);
             Thread.Sleep(20);
         }
     }
     catch (Exception ex)
     {
         Display.WriteLine("ServerListen() exception: " + ex.Message);
     }
 }
Exemplo n.º 3
0
        public void ReceiveData(object acceptSocketObject)
        {
            Socket client = (Socket)acceptSocketObject;

            client.SendTimeout    = Config.SocketSendTimeOut;
            client.ReceiveTimeout = Config.SocketReceiveTimeOut;
            int error_count = 0;

            while (flag_receive & error_count < 5)
            {
                try
                {
                    ReceiveBytes(client, out HB32Header header, out byte[] bytes);
                    //Display.TimeWriteLine(header.Flag.ToString());
                    switch (header.Flag)
                    {
                    case SocketDataFlag.DirectoryRequest:
                        ResponseDirectory(client, bytes);
                        break;

                    case SocketDataFlag.DirectorySizeRequest:
                        ResponseDirectorySize(client, bytes);
                        break;

                    case SocketDataFlag.CreateDirectoryRequest:
                        ResponseCreateDirectory(client, bytes);
                        break;

                        #region download
                    case SocketDataFlag.DownloadRequest:
                        ResponseDownloadSmallFile(client, bytes);
                        break;

                    case SocketDataFlag.DownloadFileStreamIdRequest:
                        ResponseFileStreamId(client, header, bytes, false);
                        break;

                    case SocketDataFlag.DownloadPacketRequest:
                        ResponseTransferPacket(client, header, bytes, false);
                        break;
                        #endregion

                        #region upload
                    case SocketDataFlag.UploadRequest:
                        ResponseUploadSmallFile(client, bytes);
                        break;

                    case SocketDataFlag.UploadFileStreamIdRequest:
                        ResponseFileStreamId(client, header, bytes, true);
                        break;

                    case SocketDataFlag.UploadPacketRequest:
                        ResponseTransferPacket(client, header, bytes, true);
                        break;
                        #endregion

                    case SocketDataFlag.DisconnectRequest:
                        client.Close();
                        return;

                    default:
                        throw new Exception("Invalid socket header in receiving: " + header.Flag.ToString());
                    }
                    error_count = 0;
                }
                catch (SocketException ex)
                {
                    error_count++;
                    switch (ex.ErrorCode)
                    {
                    // 远程 client 主机关闭连接
                    case 10054:
                        client.Close();
                        Display.WriteLine("connection closed (remote closed)");
                        return;

                    // Socket 超时
                    case 10060:
                        Thread.Sleep(200);
                        continue;

                    default:
                        //System.Windows.Forms.MessageBox.Show("Server receive data :" + ex.Message);
                        Display.WriteLine("Server receive data :" + ex.Message);
                        continue;
                    }
                }
                catch (Exception ex)
                {
                    error_count++;
                    if (ex.Message.Contains("Buffer receive error: cannot receive package"))
                    {
                        client.Close();
                        //Display.TimeWriteLine("connection closed (buffer received none)");
                        return;
                    }
                    if (ex.Message.Contains("Invalid socket header"))
                    {
                        client.Close();
                        Display.TimeWriteLine("connection closed : " + ex.Message);
                        return;
                    }
                    Display.TimeWriteLine("Server exception :" + ex.Message);
                    Thread.Sleep(200);
                    continue;
                }
            }
            Display.TimeWriteLine("Connection closed: error count 5");
        }