public void Start()
        {
            _server = _server ?? new ServerSocket();

            _server.Listen
                (new SocketListenerParameters
                 {
                     Port = _port,
                     DataSizeHeader = false,
                     OnReceiveData = (data, sendBack) =>
                     {
                         var dataText = Encoding.UTF8.GetString(data);
                         if(dataText == RemoteInvokeCmd)
                         {
                             Logger.Trace("Remote Invoke received.");
                             try
                             {
                                 new Thread(() => _action()).Start();
                             }
                             catch(Exception e)
                             {
                                 Logger.Error(e);
                             }
                             Logger.Trace("End remote invoke.");
                         }
                         else
                         {
                             Logger.Trace("Invalid Remote Invoke command received: {0}.", dataText);
                         }
                     }
                 });
        }
        public void TestPortInUse()
        {
            hMailServer.Application application = SingletonProvider<Utilities>.Instance.GetApp();
              application.Stop();

              var serverSocket = new ServerSocket(1, 25);
              serverSocket.StartListen();

              application.Start();
              TCPSocket sock = new TCPSocket();
              // make sure it's possible to connect to the non blocked port.

              sock.CanConnect(110);
              sock.CanConnect(143);

              //let this our temp server die.
              sock.CanConnect(25);

              // make sure that hMailServer reported an error during start up because the ports were blocked.
              Utilities.AssertReportedError();

              // restart hMailServer again. everything is now back to normal.
              application.Stop();
              application.Start();
              sock.CanConnect(25);
        }
Beispiel #3
0
 static void Main(string[] args)
 {
     ServerSocket sck = new ServerSocket(new IPEndPoint(IPAddress.Any, 8888));
     sck.SessionStarted += new BlueFox.Net.SessionEventHandler(sck_SessionStarted);
     sck.SessionEnded += new BlueFox.Net.SessionEventHandler(sck_SessionEnded);
     sck.MessageReceived += new BlueFox.Net.MessageReceivedEventHandler(sck_MessageReceived);
     sck.SessionException += new SessionEventHandler(sck_SessionException);
     sck.Start();
     Console.ReadKey();
 }
Beispiel #4
0
    // Use this for initialization
    IEnumerator Start()
    {
        Screen.sleepTimeout = SleepTimeout.NeverSleep; //屏幕常亮
        yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);
        if(Application.HasUserAuthorization(UserAuthorization.WebCam))
        {
            WebCamDevice[] devices = WebCamTexture.devices;
            deviceName = devices[0].name;
            tex = new WebCamTexture(deviceName, 960, 720, 30);
            GetComponent<Renderer>().material.mainTexture = tex;
            tex.Play();
        }

        server = new ServerSocket();
    }
Beispiel #5
0
        static void Main(string[] args)
        {
            myClient mc = new myClient(300);
            Boolean bcli = mc.Connection("127.0.0.1", 4567);
            Console.WriteLine("链接状态: " + bcli);
            FileStream sf = File.OpenRead("crossdomain.xml");
            //Flash.crossdata = new byte[sf.Length + 1];
            sf.Read(User.crossdata, 0, (int)sf.Length);
            User.crossdata[sf.Length] = (byte)0;

            MapManager.init(13);         //初始化三张地图

            ServerSocket ss = new ServerSocket();
            ss.Init(ServerConfig.CLIENTNUMBER);
            for (int i = 0; i < ServerConfig.CLIENTNUMBER; i++)
            {
                ss.AddClient(new User(300));
            }
            ss.startListen(ServerConfig.SERVER_IP, ServerConfig.SERVER_PORT);
        }
Beispiel #6
0
        public virtual void exit()
        {
            if (serverThread != null)
            {
                serverThread.exit();
                serverThread = null;
            }

            if (serverSocket != null)
            {
                try
                {
                    serverSocket.close();
                }
                catch (IOException e)
                {
                    Console.WriteLine("Closing server socket", e);
                }
                serverSocket = null;
            }
        }
        protected virtual byte[] SendRequest(string message)
        {
            WriteLog("Connecting to server socket...");
            ServerSocket.Connect(EndPoint);
            WriteLog("Server Soket connected. Sending message...");

            byte[] messageSent = $"{message}<EOF>".ToUTFBytes();
            int    byteSent    = ServerSocket.Send(messageSent);

            WriteLog("Message Sent. Waiting for server's response...");

            var wholeMessage = new List <byte[]>();

            byte[] messageReceived = new byte[2048];

            while (true)
            {
                int byteRecv = ServerSocket.Receive(messageReceived);

                if (byteRecv == 0)
                {
                    break;
                }
                else
                {
                    wholeMessage.Add(messageReceived.Take(byteRecv).ToArray());
                }

                Console.Write($"Downloaded: ");
                WriteColored(byteRecv.ToString(), ConsoleColor.Green);
                Console.WriteLine(" bytes");
            }

            WriteLog("Sutting down request.");

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

            return(wholeMessage.SelectMany(a => a).ToArray());
        }
Beispiel #8
0
        /// <summary>Sends a position update packet at the specified coordinates.
        /// This overload already assumes you have accounted for character height.</summary>
        /// <param name="x">A float marking the point along the X-Axis the bot will move to.</param>
        /// <param name="y">A float marking the point along the Y-Axis the bot will move to.</param>
        /// <param name="z">A float marking the point along the Z-Axis the bot will move to.</param>
        /// <param name="yaw">The yaw of the bot.</param>
        /// <param name="pitch">The pitch of the bot.</param>
        public void SendPositionPacket(float x, float y, float z, byte yaw, byte pitch)
        {
            if (ServerSocket == null || ServerSocket.Connected == false)
            {
                return;
            }
            if (!Players.ContainsKey(255))
            {
                return;
            }
            //if (IsValidPosition(x,y,z) == false) return; Players can move outside the map.
            Players[255].X = x;
            Players[255].Y = y;
            Players[255].Z = z;
            byte[] packet = new byte[10];
            packet[0] = (byte)0x08;            //Packet ID.
            packet[1] = (byte)255;             //Player ID of self.
            short xConverted = IPAddress.HostToNetworkOrder((short)(x * 32));

            packet[2] = (byte)(xConverted);
            packet[3] = (byte)(xConverted >> 8);
            short yConverted = IPAddress.HostToNetworkOrder((short)(z * 32));            //Account for character height.

            packet[4] = (byte)(yConverted);
            packet[5] = (byte)(yConverted >> 8);
            short zConverted = IPAddress.HostToNetworkOrder((short)(y * 32));

            packet[6] = (byte)(zConverted);
            packet[7] = (byte)(zConverted >> 8);
            packet[8] = yaw;
            packet[9] = pitch;
            try {
                ServerSocket.Send(packet);
            } catch (System.Net.Sockets.SocketException ex) {
                Log(LogType.Warning, "Error while trying to send position update packet -", ex.ToString());
            }
            PositionEventArgs e = new PositionEventArgs(255, Players[255]);

            Events.RaisePlayerMoved(e);
        }
Beispiel #9
0
 public override void StopService() =>
 (ServerSocket == null || ServerSocket.IsDisposed()
                         ? (Action)(() => { })
                         : () =>
 {
     try
     {
         if (!_acceptBroadcast)
         {
             ServerSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership,
                                          new MulticastOption(IPAddress.Parse(_multicastAddress)));
         }
         ServerSocket.Close();
     }
     catch (ObjectDisposedException)
     {
     }
     catch (Exception socketException)
     {
         OnCaughtException(socketException, EventCode.Other);
     }
 })();
Beispiel #10
0
        internal static ServerSocket HandshakeClient(HttpServer server, HttpRequest request, TcpClient tcp)
        {
            if (!request.IsWebSocket)
            {
                return(null);
            }

            byte[] response = BuildResponse(request.WebSocketKey);

            Stream stream = tcp.GetStream();

            if (server.Options.UseSecureConnection)
            {
                stream = new SslStream(stream, true);
            }

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

            ServerSocket client = server.ClientFactory.Create(server, request, tcp);

            return(client);
        }
Beispiel #11
0
        private void AcceptCallback(IAsyncResult AR)
        {
            lock (lockAccept)
            {
                Socket socket;

                try
                {
                    socket = ServerSocket.EndAccept(AR);
                    var session = new SocketSession(socket, BufferSize);

                    ClientSockets.Add(session);

                    socket.BeginReceive(session.SessionStorage, 0, BufferSize, SocketFlags.None, ReceiveCallback, socket);
                    ServerSocket.BeginAccept(AcceptCallback, null);
                }
                catch (Exception ex) // I cannot seem to avoid this (on exit when properly closing sockets)
                {
                    LogController.WriteLog(new ServerLog("*** ERROR ***: \n" + ex.Message, ServerLogType.ERROR));
                }
            }
        }
Beispiel #12
0
        //监听
        private void BtnConnect_Click(object sender, RoutedEventArgs e)
        {
            if (isliten == false)
            {
                isliten = true;

                ipaddress = IPAddress.Parse(labIpAdd.Content.ToString());
                port      = int.Parse(labPort.Text);

                mySeverSocket = new ServerSocket(port);
                mySeverSocket.Connect();
                mySeverSocket.Event_ReceiveMsg     += ShowMesg;
                mySeverSocket.Event_ClientRegister += MySeverSocket_Event_ClientRegister;
                btnConnect.Content = "关闭监听";
            }
            else
            {
                btnConnect.Content = "开始监听";
                mySeverSocket.Disconnect();
                isliten = false;
            }
        }
Beispiel #13
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldComplainIfServerPortIsAlreadyTaken() throws java.io.IOException
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldComplainIfServerPortIsAlreadyTaken()
        {
            using (ServerSocket socket = new ServerSocket(0, 0, InetAddress.LocalHost))
            {
                ListenSocketAddress   contestedAddress = new ListenSocketAddress(socket.InetAddress.HostName, socket.LocalPort);
                AssertableLogProvider logProvider      = new AssertableLogProvider();
                CommunityNeoServer    server           = CommunityServerBuilder.server(logProvider).onAddress(contestedAddress).usingDataDir(Folder.directory(Name.MethodName).AbsolutePath).build();
                try
                {
                    server.Start();

                    fail("Should have reported failure to start");
                }
                catch (ServerStartupException e)
                {
                    assertThat(e.Message, containsString("Starting Neo4j failed"));
                }

                logProvider.AssertAtLeastOnce(AssertableLogProvider.inLog(containsString("CommunityNeoServer")).error("Failed to start Neo4j on %s: %s", contestedAddress, format("Address %s is already in use, cannot bind to it.", contestedAddress)));
                server.Stop();
            }
        }
Beispiel #14
0
        void ListFilesWithDetails(Socket socket)
        {
            StringBuilder folderContents = new StringBuilder("");

            foreach (FileSystemItem item in fileSystem)
            {
                folderContents.Append(item.DetailedList() + "\n");
            }
            folderContents.Remove(folderContents.Length - 1, 1);
            folderContents.Append("\r\n");
            Write(folderContents);
            char[] charFolderContents = new char[folderContents.Length];
            folderContents.CopyTo(0, charFolderContents, 0, folderContents.Length);
            if (utf8)
            {
                ServerSocket.SendStringUTF8(charFolderContents, socket);
            }
            else
            {
                ServerSocket.SendString(charFolderContents, socket);
            }
        }
Beispiel #15
0
        private void StartConn()
        {
            if (ServerSocket != null)
            {
                ServerSocket.Close();
                ServerSocket.Dispose();
            }
            ServerSocket          = new Socket(AddressFamily.InterNetwork, SockType, ProtType);
            ServerSocket.Blocking = false;

            ConnectionTimer.Restart();
            receiveTimer.Restart();

            SocketCreated = true;

            //completely suppress the socket exception. There will always be an exception since the socket was set to non-blocking
            try
            {
                ServerSocket.Connect(IPaddress, Port);
            }
            catch { }
        }
Beispiel #16
0
 internal PortWatcher(Session session,
                      String address, int lport,
                      String host, int rport,
                      ServerSocketFactory factory)
 {
     this.session = session;
     this.lport   = lport;
     this.host    = host;
     this.rport   = rport;
     try
     {
         boundaddress = InetAddress.getByName(address);
         ss           = (factory == null) ?
                        new ServerSocket(lport, 0, boundaddress) :
                        factory.createServerSocket(lport, 0, boundaddress);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
         throw new JSchException("PortForwardingL: local port " + address + ":" + lport + " cannot be bound.");
     }
 }
Beispiel #17
0
        private void set(ServerSocket socket, object serverValue, TcpServer.ServerTaskType taskType)
        {
            this.Socket      = socket;
            this.serverValue = serverValue;
            //CommandFlags = CommandIdentity.GetCommandFlags();
            switch (taskType)
            {
            case TcpServer.ServerTaskType.ThreadPool: if (!System.Threading.ThreadPool.QueueUserWorkItem(ThreadPoolCall))
                {
                    AutoCSer.Threading.LinkTask.Task.Add(this);
                }
                return;

            case TcpServer.ServerTaskType.Timeout: AutoCSer.Threading.LinkTask.Task.Add(this); return;

            case TcpServer.ServerTaskType.TcpTask: TcpServer.ServerCallTask.Task.Add(this); return;

            case TcpServer.ServerTaskType.TcpQueue: TcpServer.ServerCallQueue.Default.Add(this); return;

            case TcpServer.ServerTaskType.Queue: socket.Server.CallQueue.Add(this); return;
            }
        }
        private static async void SocketReceiver()
        {
            while (true)
            {
                //Receive = null;

                UdpReceiveResult Result = await ServerSocket.ReceiveAsync();

                ClientEndPoint = Result.RemoteEndPoint;

                TemplateReceiver Receive = Framework.Utilities.SNetPackage.Unpacking <TemplateReceiver>(Result.Buffer);

                if (Receive.NetworkKey == "Player.Connect")
                {
                    SNetGlobalData.AddPlayer(Receive, ClientEndPoint);
                }

                if (Receive.IsGaranted)
                {
                    Receives.Add(Receive);
                }
                else
                {
                    if (Receives.Count <= 50)
                    {
                        if (!Receives.Exists(x => x.NetworkKey == Receive.NetworkKey && x.DataBytes.Length == Receive.DataBytes.Length))
                        {
                            Receives.Add(Receive);
                        }
                    }
                }

                lock (IsLock)
                {
                    IsEngine = true;
                }
            }
        }
Beispiel #19
0
 /// <summary>
 /// Запуск сервера
 /// </summary>
 /// <param name="port">порт сервера для прослушивания</param>
 public void Start(int port)
 {
     Port = port;
     try
     {
         if (SetupServerSocket())
         {
             EndPoint localEndPoint = new IPEndPoint(IPAddress.Any, Port);
             Buffer            = new byte[SizeBuffer];
             IsListeningStatus = true;
             CallStatus(ServerStatus.Start);
             ServerSocket.BeginReceiveFrom(Buffer, 0, Buffer.Length, SocketFlags.None, ref localEndPoint, new AsyncCallback(ReceiveCallback), localEndPoint);
         }
         else
         {
             CallErrorServer(ServerErrorType.StartListenError, "Failed to create socket");
         }
     }
     catch (Exception exс)
     {
         CallErrorServer(ServerErrorType.StartListenError, exс.Message);
     }
 }
Beispiel #20
0
        //ゲストからの接続を待つ処理
        public async Task <string> WaitToGuestConnect()
        {
            Adr = GetLocalIPAddress();
            //return Adr;
            try
            {
                //ServerSocketを生成する
                serverSocket = new ServerSocket(tcpPort);
                //ゲストからの接続が完了するまで待って処理を進める
                connectedSocket = await Task.Run(() => serverSocket.Accept());

                //この後はconnectedSocketに対してInputStreamやOutputStreamを用いて入出力を行ったりするが、ここでは割愛
            }
            catch (SocketException e)
            {
                e.PrintStackTrace();
            }
            catch (IOException e)
            {
                e.PrintStackTrace();
            }
            return(Adr.ToString());
        }
Beispiel #21
0
        static void Main(string[] args)
        {
            myClient mc   = new myClient(300);
            Boolean  bcli = mc.Connection("127.0.0.1", 4567);

            Console.WriteLine("链接状态: " + bcli);
            FileStream sf = File.OpenRead("crossdomain.xml");

            //Flash.crossdata = new byte[sf.Length + 1];
            sf.Read(User.crossdata, 0, (int)sf.Length);
            User.crossdata[sf.Length] = (byte)0;

            MapManager.init(13);         //初始化三张地图

            ServerSocket ss = new ServerSocket();

            ss.Init(ServerConfig.CLIENTNUMBER);
            for (int i = 0; i < ServerConfig.CLIENTNUMBER; i++)
            {
                ss.AddClient(new User(300));
            }
            ss.startListen(ServerConfig.SERVER_IP, ServerConfig.SERVER_PORT);
        }
Beispiel #22
0
        /// <summary>
        /// Send binary data to the server
        /// </summary>
        /// <param name="sendBuf">Buffer with the data to be sent</param>
        /// <param name="nrBytesToSend">Number of bytes to send from the buffer</param>
        /// <param name="receiveBuf">Buffer where the reply is to be stored</param>
        /// <returns></returns>
        public bool SendData(byte[] sendBuf, int nrBytesToSend, byte[] receiveBuf)
        {
            Received = false;
            if ((State)SM.CurrentState != State.Connected)
            {
                return(false);
            }
            try
            {
                RCVTimeout = false;
                SendTimer.Restart();


                ServerSocket.BeginSend(sendBuf, 0, nrBytesToSend, SocketFlags.None, new AsyncCallback(SendCallback), ServerSocket);
                ServerSocket.BeginReceive(receiveBuf, 0, receiveBuf.Length, 0, new AsyncCallback(ReceiveCallback), ServerSocket);
                return(true);
            }
            catch
            {
                SendTimedOut = true; //when the send fails, the receive timout can be called immediately
                return(false);
            }
        }
Beispiel #23
0
        public virtual void start()
        {
            packetFactory = new PacketFactory();

            try
            {
                serverSocket           = new ServerSocket(port);
                serverSocket.SoTimeout = 1;
            }
            catch (IOException e)
            {
                Console.WriteLine(string.Format("Server socket at port {0:D} not available: {1}", port, e));
                return;
            }

            users = new LinkedList <ProOnlineServer.User>();
            games = new LinkedList <ProOnlineServer.Game>();

            serverThread        = new ProOnlineServerThread(this);
            serverThread.Name   = "ProOnline Server Thread";
            serverThread.Daemon = true;
            serverThread.Start();
        }
Beispiel #24
0
        public void SendReboot()
        {
            while (RequestProccess.ThreadCount > 1)
            {
                Thread.Sleep(300);
                //wait...
            }

            ServerSocket.Close();
            ServerSocket.Dispose();
            ServerSocket = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ServerSocket.Bind(new IPEndPoint(IPAddress.Any, Port));
            ServerSocket.Listen(0);
            ServerSocket.BeginAccept(AcceptCallback, null);

            RebootRequest?.Invoke();
        }
Beispiel #25
0
        // callbacks...
        private void AcceptCallback(IAsyncResult results)
        {
            Socket socket;

            try
            {
                socket = ServerSocket.EndAccept(results);
            }
            catch (ObjectDisposedException)
            {
                // I cannot seem to avoid this (on exit when properly closing sockets)
                return;
            }

            this.ConnectedSockets.Add(socket);

            socket.BeginReceive(this.Buffer, 0, CommunicationProperties.PackageSize,
                                SocketFlags.None, this.ReceiveCallback, socket);

            Console.WriteLine("Client connected, waiting for request...");

            this.ServerSocket.BeginAccept(AcceptCallback, null);
        }
Beispiel #26
0
        /*
         * ------------------------------------    TCP - Guest Receive    --------------------------
         * 次に、ホストからTCP通信でIPアドレスが返されてくるので、受け取るための待ち受け状態を作っておきます。
         */
        //ホストからTCPでIPアドレスが返ってきたときに受け取るメソッド
        public async void ServerConnect()
        {
            ServerSocket serverSocket = null;
            Socket       socket       = null;
            bool         waiting      = true;
            int          tcpPort      = 3333;

            while (waiting)
            {
                try
                {
                    if (serverSocket == null)
                    {
                        serverSocket = new ServerSocket(tcpPort);
                    }
                    socket = await Task.Run(() => serverSocket.Accept());

                    //↓③で使用
                    inputDeviceNameAndIp(socket);
                    if (serverSocket != null)
                    {
                        serverSocket.Close();
                        serverSocket = null;
                    }
                    if (socket != null)
                    {
                        socket.Close();
                        socket = null;
                    }
                }
                catch (IOException e)
                {
                    waiting = false;
                    e.PrintStackTrace();
                }
            }
        }
Beispiel #27
0
        public void Start(bool waitForUserTypeExit = true)
        {
            if (Started)
            {
                throw new Exception("Server already has been started.");
            }

            Stopwatch sw = new Stopwatch();

            sw.Start();

            Initialize();
            ServerSocket.Bind(new IPEndPoint(IPAddress.Any, Port));

            ServerSocket.Listen(0);
            ServerSocket.BeginAccept(AcceptCallback, null);
            Started = true;
            ServerStarted?.Invoke();
            RunServerStartupTasks();
            sw.Stop();
            LogController.WriteLog(new ServerLog($"Server started in {sw.ElapsedMilliseconds}ms", "Server", "Start"));
            LogController.WriteLog(new ServerLog($"Running at port {Port}"));
            Console.WriteLine("Type 'exit' to stop; 'reboot' to send reboot request event...");
            string line = "";

            if (waitForUserTypeExit)
            {
                while (line != "exit")
                {
                    line = Console.ReadLine();
                    if (line == "reboot")
                    {
                        RebootRequest?.Invoke();
                    }
                }
            }
        }
Beispiel #28
0
        /// <summary>
        /// This method allows to send string data into server via ServerSocket Send property
        /// If exeption occurs in this method, Reconnect property is set to true, and this can trigger reconnect timer event.
        /// </summary>
        /// <param name="data">Data that schould be sent to server</param>
        /// <returns></returns>
        private bool Send(string data)
        {
            if (!this.Connected && !this.Connecting)
            {
                return(false);
            }


            try
            {
                byte[] BArray = Encoding.ASCII.GetBytes(data);
                DATA_OUT = BArray.Length;


                if (DATA_OUT <= BUFFER_OUT.Length)
                {
                    for (int i = 0; i < DATA_OUT; i++)
                    {
                        BUFFER_OUT[i] = BArray[i];
                    }

                    ServerSocket.Send(BUFFER_OUT, 0, DATA_OUT, SocketFlags.None);

                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                this.LastException = "|Send| " + e.Message;
                this.Stop();
                return(false);
            }
        }
Beispiel #29
0
 /// <summary>
 /// Запуск сервера
 /// </summary>
 /// <param name="port">порт сервера для прослушивания</param>
 public void Start(int port)
 {
     lock (locker)
     {
         Port = port;
         try
         {
             if (SetupServerSocket())
             {
                 ServerSocket.BeginAccept(new AsyncCallback(AcceptCallback), ServerSocket);
                 IsListeningStatus = true;
                 CallStatus(ServerStatus.Start);
             }
             else
             {
                 CallErrorServer(ServerErrorType.StartListenError, "Failed to create socket");
             }
         }
         catch (Exception exс)
         {
             CallErrorServer(ServerErrorType.StartListenError, exс.Message);
         }
     }
 }
        private void ListenerThread()
        {
            try
            {
                ServerSocket.Listen(backlog);

                while (!Quitting)
                {
                    try
                    {
                        Socket clientSocket = ServerSocket.Accept();

                        if (clientSocket != null)
                        {
                            var clientThread = new Thread(ClientThread);
                            clientThread.Start(clientSocket);
                        }
                    }
                    catch (SocketException ex)
                    {
                        if (ex.SocketErrorCode != SocketError.WouldBlock)
                        {
                            throw ex;
                        }
                        else
                        {
                            Thread.Sleep(5);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ListenerException = ex;
            }
        }
Beispiel #31
0
        private static void Listen()
        {
            serverSocket = new ServerSocket(10010);
            listening    = true;

            while (true)
            {
                Socket socket;
                try
                {
                    socket = serverSocket.Accept();
                }
                catch (Exception)
                {
                    return;
                }

                StreamReader reader  = new StreamReader(socket.InputStream);
                string       message = reader.ReadLine();

                if (message != null)
                {
                    if (message == "REQUEST_ORDERS")
                    {
                        SendOrders(socket);
                    }
                    else if (message == "UPDATES_START")
                    {
                        RecieveUpdates(socket);
                    }
                }

                reader.Close();
                socket.Close();
            }
        }
Beispiel #32
0
        //public int PointDealWidth(int point)
        //{
        //    if (point > 1)
        //    {
        //        //多个会议,合理分配端口
        //        point += point * 5;
        //    }

        //}

        /// <summary>
        /// 服务器通讯节点初始化辅助
        /// </summary>
        public static ServerSocket ServerSocketInitHelper(MeetServerSocket meetServerSocket, int point)
        {
            ServerSocket serverSocket = null;

            try
            {
                //指派一个端口
                meetServerSocket.ServerPort = point;
                //生成一个服务套接字
                meetServerSocket.ServerSocket = new ServerSocket();
                //开启侦听
                meetServerSocket.ServerSocket.Listen(IPAddress.Parse(Constant.ServerAddress), point);
                //返回的服务套接字
                serverSocket = meetServerSocket.ServerSocket;
            }
            catch (Exception ex)
            {
                LogManage.WriteLog(typeof(Constant), ex);
            }
            finally
            {
            }
            return(serverSocket);
        }
 public override CommandResult Execute(String chan, String arg2, String arg3, String arg4)
 {
     if (!String.IsNullOrEmpty(chan))
     {
         ServerSocket server = (ServerSocket)Server;
         if (chan.Length <= 12 && chan.Length >= 3 || chan.Length == 1 && chan[0] == '*')
         {
             Channel channel = server.Channels.Find(chan);
             if (channel != null)
             {
                 channel.User.Remove(ClientUser);
                 if (channel.User.Count <= 0)
                 {
                     if (channel.Name != "*")
                     {
                         server.Channels.Remove(channel);
                     }
                 }
                 return(new CommandResult(true, String.Format("{0} left channel {1}", TriggerPlayer, channel.Name)));
             }
             else
             {
                 return(new CommandResult(true, String.Format("You're not in channel {0}", channel.Name), true));
             }
         }
         else
         {
             // channel name length must be between 3 and 12
             return(new CommandResult(true, String.Format("Channel name length must be between 3 and 12"), true));
         }
     }
     else
     {
         return(new CommandResult(true, String.Format("Unknown Argument"), true));
     }
 }
Beispiel #34
0
        static void Main(string[] args)
        {
            logger.SetLog(new Log());
            ServerSocket server = new ServerSocket(new ServerFactory());

            server.Listen(9999);
            ClientSocket client = new ClientSocket(new ClientFactory());

            client.Connect("localhost", 9999);
            while (true)
            {
                string str = Console.ReadLine();
                if (str.StartsWith("file "))
                {
                    ClientConnection.GetInstance().SendFile(str.Replace("file ", ""));
                }
                else if (str.StartsWith("cmd "))
                {
                    ClientConnection.GetInstance().Send(3, 0, Encoding.UTF8.GetBytes(str.Replace("cmd ", "")));
                }
                else if (str == "exit")
                {
                    ClientConnection.GetInstance().Disconnect();
                    break;
                }
                else if (str == "quit")
                {
                    server.Shutdown();
                }
                else
                {
                    ClientConnection.GetInstance().Send(100, 9999, Encoding.UTF8.GetBytes(str));
                }
            }
            Console.ReadKey();
        }
Beispiel #35
0
        /// <summary>Sends a setblock packet at the specified coordinates.</summary>
        /// <param name="mode">Mode of whether to place or delete. 1 indicates placing, 0 indicates deleting.</param>
        /// <param name="type">The type of block being placed, as a byte.</param>
        public void SendBlockPacket(short x, short y, short z, byte mode, byte type)
        {
            if (ServerSocket == null || ServerSocket.Connected == false)
            {
                return;
            }
            if (!Players.ContainsKey(255))
            {
                return;
            }
            if (IsValidPosition(x, y, z) == false)
            {
                return;
            }
            byte[] packet = new byte[9];
            packet[0] = (byte)0x05;                                    //Packet ID.
            short xConverted = IPAddress.HostToNetworkOrder((short)x); //Position updates are * 32, dunno why..

            packet[1] = (byte)(xConverted);
            packet[2] = (byte)(xConverted >> 8);
            short yConverted = IPAddress.HostToNetworkOrder((short)z);

            packet[3] = (byte)(yConverted);
            packet[4] = (byte)(yConverted >> 8);
            short zConverted = IPAddress.HostToNetworkOrder((short)y);

            packet[5] = (byte)(zConverted);
            packet[6] = (byte)(zConverted >> 8);
            packet[7] = mode;
            packet[8] = type;
            try {
                ServerSocket.Send(packet);
            } catch (System.Net.Sockets.SocketException ex) {
                Log(LogType.Warning, "Error while trying to send block update packet -", ex.ToString());
            }
        }
Beispiel #36
0
 /// <summary>
 /// Initializes a new instance of the Session class.
 /// </summary>
 /// <param name="manager">The manager which created this session.</param>
 public Session(int id, ServerSocket manager)
 {
     this.Id = id;
     this.Manager = manager;
 }
 public MainWindowViewModel()
 {
     this.server = new ServerSocket(1500);
 }
Beispiel #38
0
 public Session(int id, ServerSocket ServerSocket)
 {
     this.Manager = ServerSocket;
     this.Id = id;
 }
 public ServerSidePacketHandler(ServerSocket serverSocket)
 {
     this.serverSocket = serverSocket;
 }
 private void Awake()
 {
     mInstance = this;
 }
Beispiel #41
0
        public void AyncTcpServer()
        {
            ServerSocket serverSocket = new ServerSocket();
            serverSocket.Bind(9900);

            serverSocket.AddMessageHandler<SampleMessage>(SampleMessageHandler);

            // Get host related information.
            IPAddress[] addressList = Dns.GetHostEntry(Environment.MachineName).AddressList;

            // Get endpoint for the listener.
            IPEndPoint localEndPoint = new IPEndPoint(addressList[addressList.Length - 1], 9900);

            long totalTime = 0;
            const int msgs = (int)1e5;
            int msgLength = 0;
            Action action = () =>
                {
                    ClientSocket clientSocket = new ClientSocket();
                    clientSocket.Connect(localEndPoint);

                    Assert.IsTrue(clientSocket.Connected);

                    Stopwatch sw = Stopwatch.StartNew();
                    Serializer serializer = new Serializer();

                    var sample = new SampleMessage { X = 38 };
                    var msg = serializer.Serialize(sample);
                    msgLength = msg.Length;

                    for (int i = 0; i < msgs; i++)
                    {
                        clientSocket.Send(sample);
                    }

                    sw.Stop();

                    Interlocked.Add(ref totalTime, sw.ElapsedMilliseconds);

                    SpinWait.SpinUntil(() => counter == msgs, 2000);

                    //networkStream.Close();
                    clientSocket.Close();
                };

            List<Action> actions = new List<Action>();
            int numOfClients = 1;

            for (int i = 0; i < numOfClients; i++)
            {
                actions.Add(action);
            }

            Stopwatch sw2 = Stopwatch.StartNew();
            Parallel.Invoke(actions.ToArray());

            if (!Debugger.IsAttached)
                SpinWait.SpinUntil(() => counter == msgs * numOfClients, 2000);
            else
            {
                SpinWait.SpinUntil(() => counter == msgs * numOfClients, 60000);
            }

            sw2.Stop();

            Console.WriteLine("Num Of Msgs: {0:###,###}", counter);
            Console.WriteLine("Average for each client {0}ms", totalTime / actions.Count);
            Console.WriteLine("Average Speed for each client: {0:###,###}msgs/s", (msgs / (totalTime / actions.Count)) * 1000);
            Console.WriteLine("Total time: {0}ms", sw2.ElapsedMilliseconds);
            Console.WriteLine("Msgs/s {0:###,###}", (counter / sw2.ElapsedMilliseconds) * 1000);
            Console.WriteLine("Msg length {0}bytes", msgLength);
            Assert.AreEqual(msgs * numOfClients, counter, "Not all msgs received");
        }