Пример #1
1
        public void Socket_SendReceive_Success()
        {
            string path = GetRandomNonExistingFilePath();
            var endPoint = new UnixDomainSocketEndPoint(path);
            try
            {
                using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
                {
                    server.Bind(endPoint);
                    server.Listen(1);

                    client.Connect(endPoint);
                    using (Socket accepted = server.Accept())
                    {
                        var data = new byte[1];
                        for (int i = 0; i < 10; i++)
                        {
                            data[0] = (byte)i;

                            accepted.Send(data);
                            data[0] = 0;

                            Assert.Equal(1, client.Receive(data));
                            Assert.Equal(i, data[0]);
                        }
                    }
                }
            }
            finally
            {
                try { File.Delete(path); }
                catch { }
            }
        }
Пример #2
0
    //static void Main(string[] args, int a)
    public static void send()
    {
        String name = Id.name;
            String a2 = link.a.ToString();
            int y = 9;
            String a3 = y.ToString();
            Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            sck.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 23));
            sck.Listen(0);

            Socket acc = sck.Accept();
        // all the data will  be sent in one buffer.
            byte[] buffer = Encoding.Default.GetBytes(name + a2 + a3);

            acc.Send(buffer, 0, buffer.Length, 0);
            buffer = new byte[255];
            int rec = acc.Receive(buffer, 0, buffer.Length, 0);
            Array.Resize(ref buffer, rec);

            Console.WriteLine("Received: {0}", Encoding.Default.GetString(buffer));

            sck.Close();
            acc.Close();

            Console.Read();
    }
Пример #3
0
	public static void Main(String []argv)
	{
		IPAddress ip = IPAddress.Loopback;
		Int32 port=1800;
		if(argv.Length>0)
			port = Int32.Parse(argv[0]);	
		IPEndPoint ep = new IPEndPoint(ip,port);
		Socket ss = new Socket(AddressFamily.InterNetwork , 
			SocketType.Stream , ProtocolType.Tcp);
		try
		{
			ss.Bind(ep);
		}
		catch(SocketException err)
		{
			Console.WriteLine("** Error : socket already in use :"+err);
			Console.WriteLine("           Please wait a few secs & try");	
		}
		ss.Listen(-1);
		Console.WriteLine("Server started and running on port {0}.....",port);
		Console.WriteLine("Access URL http://localhost:{0}",port);
		Socket client = null;
		while(true)
		{
			client=ss.Accept();
			SocketMessenger sm=new SocketMessenger(client);
			sm.Start();
		}
		Console.WriteLine(client.LocalEndPoint.ToString()+" CONNECTED ");
		ss.Close();
	}
Пример #4
0
    // main.. how we start it all up
    static int Main(string[] args)
    {
        // args checker
        if (args.Length != 4)
        {
            System.Console.WriteLine("port_redir.exe <listenIP> <listenPort> <connectIP> <connectPort>");
            return 1;
        }
        // Our socket bind "function" we could just as easily replace this with
        // A Connect_Call and make it a true gender-bender
        IPEndPoint tmpsrv = new IPEndPoint(IPAddress.Parse(args[0]), Int32.Parse(args[1]));
        Socket ipsrv = new Socket(tmpsrv.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
        ipsrv.Bind(tmpsrv);
        ipsrv.Listen(10);

        // loop it so we can continue to accept
        while (true)
        {
            try
            {
                // block till something connects to us
                Socket srv = ipsrv.Accept();
                // Once it does connect to the outbound ip:port
                Socket con = Connect_Call(args[2], Int32.Parse(args[3]));
                // Read and write back and forth to our sockets.
                Thread SrvToCon = new Thread(() => Sock_Relay(srv, con));
                SrvToCon.Start();
                Thread ConToSrv = new Thread(() => Sock_Relay(con, srv));
                ConToSrv.Start();
            }
            catch (Exception e) { Console.WriteLine("{0}", e); }
        }
    }
Пример #5
0
	static void Main (string [] args)
	{
		byte [] buffer = new byte [10];

		IPAddress ipAddress = IPAddress.Loopback;
		IPEndPoint localEndPoint = new IPEndPoint (ipAddress, 12521);

		Socket listener = new Socket (AddressFamily.InterNetwork,
			SocketType.Stream, ProtocolType.Tcp);

		listener.Bind (localEndPoint);
		listener.Listen (5);

		Socket handler = listener.Accept ();

		int bytesRec = handler.Receive (buffer, 0, 10, SocketFlags.None);

		string msg = Encoding.ASCII.GetString (buffer, 0, bytesRec);
		if (msg != "hello") {
			string dir = AppDomain.CurrentDomain.BaseDirectory;
			using (StreamWriter sw = File.CreateText (Path.Combine (dir, "error"))) {
				sw.WriteLine (msg);
			}
		}

		handler.Close ();

		Thread.Sleep (200);
	}
Пример #6
0
    public static void StartListening()
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1024];

        // Establish the local endpoint for the socket.
        // Dns.GetHostName returns the name of the 
        // host running the application.
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);

        // Bind the socket to the local endpoint and 
        // listen for incoming connections.
        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(10);

            // Start listening for connections.
            while (true)
            {
                Console.WriteLine("Waiting for a connection...");
                // Program is suspended while waiting for an incoming connection.
                Socket handler = listener.Accept();
                data = null;

                // Show the data on the console.
                Console.WriteLine("Text received : {0}", data);
                byte[] msg = null;
                // Echo the data back to the client.
                while (true)
                {
                    data = Guid.NewGuid().ToString();
                    msg = Encoding.ASCII.GetBytes(data);
                    handler.Send(msg);
                    Console.WriteLine("Text sent : {0} {1}", data, DateTime.Now.ToString());
                    
                    System.Threading.Thread.Sleep(1000);
                }

                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("\nPress ENTER to continue...");
        Console.ReadLine();

    }
Пример #7
0
    private static void AcceptTcpClients(Socket serverSocket)
    {
        while (true) {
            // accept client
            Socket clientSocket = serverSocket.Accept();
            _logger.Log(string.Format ("accepted client from {0}", Utils.IPAddressToString(clientSocket.RemoteEndPoint)));

            Concurrency.StartThread(() => HandleTcpClient(clientSocket), "server handle client", _logger);
        }
    }
Пример #8
0
		private void StartAcceptingConnections(Socket socket)
		{
			var task = new Task(() =>
			{
				while (!socket.IsDisposed)
				{
					var connection = socket.Accept();
					if (connection != null)
						StartReceivingMessages(connection, new byte[socket.ReceiveBufferSize]);
				}
			}, TaskCreationOptions.LongRunning);
			task.Start();
		}
Пример #9
0
    private void StartListeningInternal()
    {
        byte[] bytes = new Byte[MessageSize];

        try
        {
            var localEndPoint = new IPEndPoint(IpHelper.Ip, DefaultPort);

            _listener = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _listener.Bind(localEndPoint);
            _listener.Listen(MaxConnections);

            while (!_aborted)
            {
                Socket handler = _listener.Accept();
                var data = "";

                while (!_aborted)
                {
                    try
                    {
                        bytes = new byte[Transport.PacketSize];
                        var bytesRec = handler.Receive(bytes);
                        data += Encoding.ASCII.GetString(bytes,0,bytesRec);

                        if (data.IndexOf(Transport.EndFlag) > -1)
                            break;
                    }
                    catch (Exception ex)
                    {
                        Debug.Log(ex);
                    }
                }

                // Echo the data back to the client.
                var result = _serverProtocol.ProcessRequest(data);
                if (result!=null)
                    handler.Send(Encoding.ASCII.GetBytes(result+Transport.EndFlag));

                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }

            _listener.Shutdown(SocketShutdown.Both);
            _listener.Close();
        }
        catch (Exception e)
        {
            Debug.Log(e);
        }
    }
Пример #10
0
    static void ticksrv_srv()
    {
        Socket csock = null;
        int sync_err = 0;
        ticksrv_state = true;
        ticksrv_sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        ticksrv_sck.Bind(new IPEndPoint(IPAddress.Parse(ticksrv_Ip), ticksrv_Port));
        ticksrv_sck.Listen(5);
        ticksrv_sck.ReceiveTimeout = 12000;
        while (true)
        {
            csock = null;
            try
            {
                Console.WriteLine("Wait tick client in ");
                csock = ticksrv_sck.Accept();  // 等待Client 端連線
            }
            catch
            {
                Console.WriteLine("Wait tick client , error ");
            }
            if (csock != null)
            {
                ticksrv_state = true;
                sync_err = 0;
                Console.WriteLine("quote tick srv con in");
                Thread.Sleep(1);
            }
            while (ticksrv_state == true)
            {
                while (Quote.msg.ticksrv_kgidata_flash == false)
                    Thread.Sleep(1);

                byte[] tick_data;
                try
                {
                    tick_data = Encoding.ASCII.GetBytes("tick_data;" + Quote.msg.Get_tick_P().ToString() + ";" + Quote.msg.Get_tick_v().ToString() + ";" + Quote.msg.Get_tick_t().ToString() + ";e");
                    csock.Send(tick_data);
                }
                catch
                {
                    sync_err++;
                }
                if (sync_err > 1)
                {
                    ticksrv_state = false;
                    break;
                }
            }
        }
    }
    public SynchronousSocketListener(int port)
    {
        // Data buffer for incoming data.
        bytes = new Byte[1024];

        // Establish the local endpoint for the socket.
        // Dns.GetHostName returns the name of the
        // host running the application.
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);

        // Bind the socket to the local endpoint and
        // listen for incoming connections.
        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(10);

            // Start listening for connections.
            //while (true)
            {
                Console.WriteLine("Waiting for a connection...");
                // Program is suspended while waiting for an incoming connection.
                handler = listener.Accept();

                /*
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
                */
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        /*
        Console.WriteLine("\nPress ENTER to continue...");
        Console.Read();
        */
    }
Пример #12
0
    public static int Main(String[] args)
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[1 << 20];

        IPEndPoint localEndPoint = new IPEndPoint(new IPAddress(new byte[] { 127, 0, 0, 1 }), 5001);
        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        try
        {
            listener.Bind(localEndPoint);
            listener.Listen(10);

            // Start listening for connections.
            while (true)
            {
                Console.WriteLine("Waiting for a connection...");
                Socket handler = listener.Accept();
                Console.WriteLine("Connected");

                try
                {
                    while (true)
                    {
                        handler.Receive(bytes);
                    }
                }
                catch (Exception) { }

                Console.WriteLine("Connection terminated");
                try { handler.Shutdown(SocketShutdown.Both); }
                catch (Exception) { }
                try { handler.Close(); }
                catch (Exception) { }
                try { handler.Dispose(); }
                catch (Exception) { }
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
        return 0;
    }
Пример #13
0
    public static void Main(String[] args)
    {
        KDTree = new KdTree<float,int> (2, new FloatMath ());

            idMap = new Dictionary<int, AskObject> ();
            maxObjectId = 0;

            Socket listener = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listener.Bind (new IPEndPoint (IPAddress.Any, 1234));
            listener.Listen (100);

            while (true) {
                Socket handler = listener.Accept ();
                ASKServer askServer = new ASKServer (handler);
                Thread mythread = new Thread (askServer.run);
                mythread.Start ();
            }
    }
    static TcpClient AcceptIncoming(Socket listeningSocket)
    {
        try
        {
            var tcpSocket = listeningSocket.Accept();
            tcpSocket.Blocking = true;
            Debug.Log("accepted incoming socket");
            return new TcpClient {Client = tcpSocket};
        }
        catch (SocketException ex)
        {
            if (ex.ErrorCode == (int)SocketError.WouldBlock)
                return null;

            Debug.Log("SocketException in AcceptIncoming: " + ex);
            throw (ex);
        }
    }
Пример #15
0
	private Socket _listenSocket; // прослушивающий сокет
 
	
	 
	
	protected  void StartCore()
	{
		// создаем прослушивающий сокет
		//Log.Info ("sdfsdfds");
		Console.WriteLine ("sdddddd");
		_listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		_listenSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.AcceptConnection, true);
		// _listenSocket.SetIPProtectionLevel(IPProtectionLevel.Unrestricted);
		_listenSocket.Bind(_serverEndPoint);
		_listenSocket.Listen(10);
		Log.Info ("dffffff");
		Socket s =  _listenSocket.Accept ();
		s.Send (System.Text.Encoding.ASCII.GetBytes("sendMessage"));
		
		//_cancellationSource = new CancellationTokenSource();
		
		// начать цикл приема входящих подключений
		//StartAccepting(); 
	}
Пример #16
0
Файл: test.cs Проект: mono/gert
	public void Serve ()
	{
		// Create the server socket
		Socket sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		sock.Bind (new IPEndPoint (IPAddress.Loopback, 54321));
		sock.Listen (5);

		// Wait for connection
		iStarted.Set ();
		Socket sock2 = sock.Accept ();

		// connection made - wait for http request
		byte [] data = new byte [1000];
		sock2.Receive (data);

		ASCIIEncoding enc = new ASCIIEncoding ();

		// Send the response - chunked responses will very likely be
		// sent as a series of Send() calls.
		sock2.Send (enc.GetBytes ("HTTP/1.1 200 OK\r\n"));
		sock2.Send (enc.GetBytes ("Transfer-Encoding: chunked\r\n"));
		sock2.Send (enc.GetBytes ("\r\n"));
		sock2.Send (enc.GetBytes ("8\r\n"));
		sock2.Send (enc.GetBytes ("01234567\r\n"));
		sock2.Send (enc.GetBytes ("10\r\n"));
		sock2.Send (enc.GetBytes ("0123456789abcdef\r\n"));
		sock2.Send (enc.GetBytes ("7\r\n"));
		sock2.Send (enc.GetBytes ("abcdefg\r\n"));
		sock2.Send (enc.GetBytes ("9\r\n"));
		sock2.Send (enc.GetBytes ("hijklmnop\r\n"));
		sock2.Send (enc.GetBytes ("a\r\n"));
		sock2.Send (enc.GetBytes ("qrstuvwxyz\r\n"));
		sock2.Send (enc.GetBytes ("0\r\n"));
		sock2.Send (enc.GetBytes ("\r\n"));

		// Close the sockets
		sock2.Close ();
		sock.Close ();
	}
    public DataReceive(String port)
    {
        while (Static_Lock.lockCondition == true) ;
        Static_Lock.lockCondition = true;
        IPEndPoint ip = new IPEndPoint(IPAddress.Any, Convert.ToInt32(port));
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        Console.WriteLine("Binding--Data");
        socket.Bind(ip);
        Console.WriteLine("Bind successful");
        socket.Listen(10);
        //Console.WriteLine("Waiting for a client...//Data Receive called");

        Socket client = socket.Accept();

        IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
        ipaddress = clientep.Address.ToString();
        //Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);
        byte[] data = new byte[100];
        int receivedDataLength = client.Receive(data);
        text= Encoding.ASCII.GetString(data, 0, receivedDataLength);
        try
        {

            client.Send(Encoding.ASCII.GetBytes("Received"));
           // Console.WriteLine("Acknowledgement sending");
        }
        catch (SocketException e)
        {
            Console.WriteLine("Problem with receiving error:"+e);
        }

        //Console.WriteLine("Disconnected from {0}+1st", clientep.Address);
        client.Close();
        socket.Close();
        Console.WriteLine("Binding--Data--close");
        Static_Lock.lockCondition = false;
        //Console.WriteLine("Disconnected from {0}+2nd", clientep.Address);
    }
Пример #18
0
    static void Main()
    {
        Console.WriteLine("Esperando para conexión...!!");

            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 8000);
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            sock.Bind(localEndPoint);
            sock.Listen(10);
            Socket handler = sock.Accept();
            Console.WriteLine("Conexión recibida de " + ((IPEndPoint)handler.RemoteEndPoint).Address.ToString());
            String data = null;

            byte[] bytes;

        string[] directorios = Directory.GetFiles(@"c:\");
        JavaScriptSerializer oSerializer = new JavaScriptSerializer();
            string dirJSON = oSerializer.Serialize(directorios);

            while (true)
            {
                bytes = new byte[1024];
                int bytesRec = handler.Receive(bytes);
                data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                Console.WriteLine(data);

                if (data.IndexOf("<DIR>") > -1)
                {
            Console.WriteLine("Texto recibido: {0}", data);
                    byte[] msg = Encoding.ASCII.GetBytes(dirJSON);
                handler.Send(msg);
            handler.Shutdown(SocketShutdown.Both);
            handler.Close();
            break;
                }

             }
    }
Пример #19
0
Файл: test.cs Проект: mono/gert
	static int Main ()
	{
		Socket server = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
						ProtocolType.Tcp);
		IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, 1234);
		server.Bind (ep);
		server.Listen (1);

		Socket client = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
						ProtocolType.Tcp);
		client.Connect (ep);

		Socket accepted = server.Accept ();

		string endPoint = accepted.RemoteEndPoint.ToString ();
		if (endPoint == null || endPoint.Length == 0)
			return 1;

		client.Close ();
		if (endPoint != accepted.RemoteEndPoint.ToString ())
			return 2;
		return 0;
	}
Пример #20
0
 private static void Main()
 {
     // 서버 소켓 생성
       Socket mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
       // 종단점 생성
       IPEndPoint point = new IPEndPoint(IPAddress.Loopback, 8192);
       // 소켓 바인딩
       mySocket.Bind(point);
       // 소켓을 대기 상태로 둠
       mySocket.Listen(1);
       // 연결한 소켓을 받아들임
       mySocket = mySocket.Accept();
       // 파일을 엶
       FileStream fileStr = new FileStream("music.mp3", FileMode.Open, FileAccess.Read);
       // 파일 크기를 가져옴
       int fileLength = (int)fileStr.Length;
       // 파일 크기를 클라이언트에 전송하기 위해 바이트 배열로 변환
       byte[] buffer = BitConverter.GetBytes(fileLength);
       // 파일 크기 전송
       mySocket.Send(buffer);
       // 파일을 보낼 횟수
       int count = fileLength / 1024 + 1;
       // 파일을 읽기 위해 BinaryReader 객체 생성
       BinaryReader reader = new BinaryReader(fileStr);
       // 파일 송신 작업
       for (int i = 0; i < count; i++)
       {
      // 파일을 읽음
      buffer = reader.ReadBytes(1024);
      // 읽은 파일을 클라이언트로 전송
      mySocket.Send(buffer);
       }
       // 종료 작업
       reader.Close();
       mySocket.Close();
 }
Пример #21
0
 public override Task <Socket> AcceptAsync(Socket s) =>
 Task.Run(() => s.Accept());
Пример #22
0
 public static Socket socket_accept(Socket sock)
 {
     return sock.Accept();
 }
Пример #23
0
        public void StartListening()
        {
            var    ipPoint      = new IPEndPoint(IPAddress.Parse(ipAddress), port);
            Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            Socket handler      = null;

            try
            {
                listenSocket.Bind(ipPoint);
                listenSocket.Listen(10);
                logger.Log(SocketServiceMessage.socketStartListening);

                while (true)
                {
                    handler = listenSocket.Accept();
                    var    builder = new StringBuilder();
                    int    bytes   = 0;
                    byte[] data    = new byte[256];

                    do
                    {
                        bytes = handler.Receive(data);
                        builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
                    }while (handler.Available > 0);

                    string inputInfo = builder.ToString();
                    var    tpModel   = JsonSerializer.Deserialize <MxMultiplicationInputModel>(inputInfo);
                    logger.Log(inputInfo);
                    var mxResponse1 = dbSocket.GetData(tpModel.MX1Name);
                    var mxResponse2 = dbSocket.GetData(tpModel.MX2Name);
                    var result      = new OperationResult <List <List <int> > >();

                    if (mxResponse1.Status == OperationStatus.Ok && mxResponse2.Status == OperationStatus.Ok)
                    {
                        matrix1 = mxResponse1.Data;
                        matrix2 = mxResponse2.Data;

                        if (MatrixOperations.CheckMultiplyCondition(matrix1, matrix2))
                        {
                            List <List <int> > multiRes = MatrixOperations.MultiplyMatrices(matrix1, matrix2);
                            result.Data   = CutMatrixBuilder.Build(multiRes, tpModel.RowBegin, tpModel.RowEnd, tpModel.ColBegin, tpModel.ColEnd);
                            result.Status = OperationStatus.Ok;
                        }
                        else
                        {
                            result.Status  = OperationStatus.Error;
                            result.Message = Errors.MultiplyConditionFailed;
                        }
                    }
                    else
                    {
                        result.Status  = OperationStatus.Error;
                        result.Message = mxResponse1.Status == OperationStatus.Error ? mxResponse1.Message : mxResponse2.Message;
                    }


                    data = Encoding.Unicode.GetBytes(JsonSerializer.Serialize(result));
                    handler.Send(data);
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                handler?.Shutdown(SocketShutdown.Both);
                listenSocket.Close();
                logger.Log(SocketServiceMessage.socketReloading);
                StartListening();
            }
        }
Пример #24
0
    static int Accept(Dictionary <String, String> args)
    {
        IInt32SequenceFactory sequenceFactory = GetSequenceFactory(args);

        if (sequenceFactory == null)
        {
            Console.WriteLine("Invalid sequence specified.");
            return(1);
        }

        using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
            int    port = DefaultPort;
            string portString;
            if (args.TryGetValue("port", out portString))
            {
                if (!Int32.TryParse(portString, out port))
                {
                    Console.WriteLine("Invalid port string.");
                    return(1);
                }
            }

            IPEndPoint any = new IPEndPoint(IPAddress.Any, port);

            try { listener.Bind(any); }
            catch (Exception ex) {
                Console.WriteLine("Bind failed.");
                ShowException(ex);
                return(1);
            }

            try { listener.Listen(5); }
            catch (Exception ex) {
                Console.WriteLine("Listen failed.");
                ShowException(ex);
                return(1);
            }

            for (; ;)
            {
                Socket client;

                Console.WriteLine("Waiting for client to connect at port: " + listener.LocalEndPoint);
                try { client = listener.Accept(); }
                catch (Exception ex) {
                    Console.WriteLine("Accept failed.");
                    ShowException(ex);
                    break;
                }

                Console.WriteLine("Accepted client.");

                try {
                    RunClient(args, client, sequenceFactory);
                }
                catch (Exception ex) {
                    ShowException(ex);
                }
                finally {
                    client.Close();
                }

                Console.WriteLine();
            }
        }

        return(0);
    }
Пример #25
0
        public void ListenForRequest()
        {
            while (true)
            {
                using (Socket clientSocket = socket.Accept())
                {
                    //Get clients IP
                    IPEndPoint clientIP       = clientSocket.RemoteEndPoint as IPEndPoint;
                    EndPoint   clientEndPoint = clientSocket.RemoteEndPoint;
                    //int byteCount = cSocket.Available;
                    int bytesReceived = clientSocket.Available;
                    if (bytesReceived > 0)
                    {
                        //Get request
                        byte[] buffer    = new byte[bytesReceived];
                        int    byteCount = clientSocket.Receive(buffer, bytesReceived, SocketFlags.None);
                        string request   = new string(Encoding.UTF8.GetChars(buffer));
                        Debug.Print(request);

                        string response = "";

                        //Blink the onboard
                        string[] words = request.Split(' ');

                        if (words[1] == "1")
                        {
                            if (words[0] == "ON")
                            {
                                adjust_pwm(ref this.pwm_top, ref this.pwm_top_val);
                            }

                            //this.sol_under.Write(true);
                            Thread.Sleep(TEMP);
                            this.pwm_top.DutyCycle = 0;
                            response = this.pwm_top_val.ToString();
                        }
                        else if (words[1] == "2")
                        {
                            if (words[0] == "ON")
                            {
                                adjust_pwm(ref this.pwm_bot, ref this.pwm_bot_val);
                            }

                            //this.sol_under.Write(true);
                            Thread.Sleep(TEMP);
                            this.pwm_bot.DutyCycle = 0.0;
                            response = this.pwm_bot_val.ToString();
                        }
                        else if (words[1] == "3")
                        {
                            if (words[0] == "ON")
                            {
                                adjust_pwm(ref this.pwm_left, ref this.pwm_left_val);
                            }

                            //this.sol_under.Write(true);
                            Thread.Sleep(TEMP);
                            this.pwm_left.DutyCycle = 0.0;
                            response = this.pwm_left_val.ToString();
                        }
                        else if (words[1] == "4")
                        {
                            if (words[0] == "ON")
                            {
                                adjust_pwm(ref this.pwm_right, ref this.pwm_right_val);
                            }

                            //this.sol_under.Write(true);
                            Thread.Sleep(TEMP);
                            this.pwm_right.DutyCycle = 0.0;
                            response = this.pwm_right_val.ToString();
                        }
                        else if (words[1] == "5") //brake
                        {
                            if (words[0] == "OFF")
                            {
                                //this.sol_under.Write(false);
                                if (this.adc)
                                {
                                    Debug.Print(get_current(this.adc_brake).ToString());
                                }
                            }
                            else if (words[0] == "ON")
                            {
                                //this.sol_under.Write(true);
                            }
                        }
                        else if (words[1] == "INCREMENT")
                        {
                            this.desired_current += 0.10;
                            this.TEMP            += 1;
                            Debug.Print(this.TEMP.ToString());
                            response = this.desired_current.ToString();
                        }
                        else if (words[1] == "DECREMENT")
                        {
                            this.desired_current -= 0.10;
                            this.TEMP            -= 1;
                            Debug.Print(this.TEMP.ToString());
                            response = this.desired_current.ToString();
                        }
                        else if (words[1] == "GETVOLTAGE")
                        {
                            response = "a";
                        }
                        else if (words[1] == "GET_DESIRED_CURRENT")
                        {
                            response = this.desired_current.ToString();
                        }
                        else if (words[1] == "TOGGLEADC")
                        {
                            this.adc = !this.adc;
                            response = this.adc.ToString();
                        }
                        else if (words[1] == "SET_DESIRED_CURRENT")
                        {
                            this.desired_current = Convert.ToDouble(words[2]);

                            Boolean success = true;

                            if (adc)
                            {
                                success &= adjust_pwm(ref this.pwm_left, ref this.adc_left, ref this.pwm_left_val);
                                success &= adjust_pwm(ref this.pwm_right, ref this.adc_right, ref this.pwm_right_val);
                                success &= adjust_pwm(ref this.pwm_top, ref this.adc_top, ref this.pwm_top_val);
                                success &= adjust_pwm(ref this.pwm_bot, ref this.adc_bot, ref this.pwm_bot_val);
                            }

                            if (success)
                            {
                                response = "success";
                            }
                            else
                            {
                                response = "fail";
                            }
                        }

                        //Compose a response
                        string header = "HTTP/1.0 200 OK\r\nContent-Type: text; charset=utf-8\r\nContent-Length: " + response.Length.ToString() + "\r\nConnection: close\r\n\r\n";
                        clientSocket.Send(Encoding.UTF8.GetBytes(header), header.Length, SocketFlags.None);
                        clientSocket.Send(Encoding.UTF8.GetBytes(response), response.Length, SocketFlags.None);
                    }
                }
            }
        }
Пример #26
0
    public static void StartListening()
    {
        // Data buffer for incoming data.
        byte[] bytes = new Byte[16000];

        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

        // Create a TCP/IP socket.
        Socket listener = new Socket(AddressFamily.InterNetwork,
            SocketType.Stream, ProtocolType.Tcp);
        Console.Write("\"gen\" - Генерировать RSA ключи\n\"enc\" - Выбрать файл для шифрования и отправки\n");
           // Console.ReadLine();
        string answer = null;
        byte[] aesKey = null;
        answer = Console.ReadLine();
        if (answer == "gen")
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(2048);
            string rsaKey = rsa.ToXmlString(true);
            File.WriteAllText("c:\\private.txt", rsaKey);
            Console.Write("Ключи RSA были успешно сгенерированы и сохранены.\n\n");
        }
        Console.Write("\"gen\" - Генерировать RSA ключи\n\"enc\" - Выбрать файл для шифрования и отправки\n");
        answer = Console.ReadLine();
        if (answer == "enc")
        {
            // Bind the socket to the local endpoint and
            // listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);

                // Start listening for connections.
                while (true)
                {
                    Console.WriteLine("Ожидание соединения...");
                    // Program is suspended while waiting for an incoming connection.
                    Socket handler = listener.Accept();
                    data = null;
                    Console.Write("Нажмите Enter, чтобы выбрать файл для отправки");
                    Console.Read();
                    OpenFileDialog dlg = new OpenFileDialog();
                    dlg.AddExtension = true;
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        using (AesCryptoServiceProvider myAes = new AesCryptoServiceProvider())
                        {
                            myAes.KeySize = 256;
                            myAes.GenerateKey();
                           // myAes.Padding = PaddingMode.None;
                            aesKey = myAes.Key;
                            Console.WriteLine(dlg.FileName);
                            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                            rsa.FromXmlString(File.ReadAllText("c:\\private.txt"));
                            byte[] df = rsa.Encrypt(myAes.Key, false);
                            byte[] mes = Encoding.ASCII.GetBytes("{Key}");

                            byte[] newArray = new byte[df.Length + mes.Length];
                            Array.Copy(mes, 0, newArray, 0, mes.Length);
                            Array.Copy(df, 0, newArray, mes.Length, df.Length);
                            handler.Send(newArray);
                        }
                    }
                    Thread.Sleep(1000);
                    // An incoming connection needs to be processed.
                    while (true)
                    {
                        bytes = new byte[1024];
                        int bytesRec = handler.Receive(bytes);

                        data = Encoding.UTF8.GetString(bytes, 0, bytesRec);
                        if (data.IndexOf("Ключ") > -1)
                        {
                            Console.Write("\nКлюч был успешно отправлен!\n");
                            byte[] encMes = EncryptFile(dlg.FileName, aesKey);
                            handler.Send(encMes);
                            Console.Write("\nФайл был успешно зашифрован и отправлен!\n");
                            handler.Shutdown(SocketShutdown.Both);
                            handler.Close();
                            break;
                        }
                    }
                    //Thread.Sleep(1000);

                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

        }
        Console.WriteLine("\nНажмите Enter для продолжения\n");
        Console.Read();
    }
Пример #27
0
        static void Main(string[] args)
        {
            Output("Enhanced Honeywords System v1.0\n");
            Output("Distributed under the GNU General Public License (GPL)\n\n");

            #region Network Connections
            int        padBeforeDone = Output("Starting network connections.");
            IPEndPoint ipep          = new IPEndPoint(IPAddress.Any, 9051);
            Socket     newsock       = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            newsock.Bind(ipep);
            newsock.Listen(10);
            Done(padBeforeDone);
            padBeforeDone = Output("Honeychecker started. Waiting for Login Server.");
            Done(padBeforeDone);
            Socket     client   = newsock.Accept();
            IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
            padBeforeDone = Output("Connected with " + clientep.Address.ToString() + " at port " + clientep.Port.ToString());
            Done(padBeforeDone);
            #endregion

            while (true)
            {
                byte[] data = new byte[1024];
                int    recv = client.Receive(data);
                if (recv == 0)
                {
                    break;
                }

                int    id         = BitConverter.ToInt32(data, 0);
                int    index      = BitConverter.ToInt32(data, 4);
                byte[] sweetbytes = new byte[430];
                Buffer.BlockCopy(data, 8, sweetbytes, 0, 430); // sweetbytes, i.e., encrypted passwords

                int    c       = 0;
                int    lastn   = 0;
                string connStr = @"Data Source=(LocalDB)\MSSQLLocalDB; AttachDbFilename=|DataDirectory|\indexdb.mdf; Integrated Security=True; Connect Timeout=10;";
                using (SqlConnection conn = new SqlConnection(connStr))
                {
                    conn.Open();
                    using (SqlCommand command = new SqlCommand("SELECT indexOfPassword, n FROM IndexTable WHERE Id=@id", conn))
                    {
                        command.Parameters.AddWithValue("@Id", id);
                        using (var rdr = command.ExecuteReader())
                        {
                            if (!rdr.HasRows)
                            {
                                Output("Fatal error! Id cannot be found: " + id.ToString() + "\n");
                                Output("This may break the synchronization!\n");
                                continue;
                            }

                            while (rdr.Read())
                            {
                                c     = (int)rdr["indexOfPassword"];
                                lastn = (int)rdr["n"];
                            }
                        }
                    }
                }

                string timestamp = DateTime.UtcNow.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture);

                //padBeforeDone = Output(string.Format("{0}   Received {1} bytes of data.\n", timestamp, recv));

                data = new byte[4 + 430];
                if (index == c)
                {
                    Buffer.BlockCopy(BitConverter.GetBytes(0), 0, data, 0, 4);
                }
                else
                {
                    Buffer.BlockCopy(BitConverter.GetBytes(1), 0, data, 0, 4);
                }

                Stopwatch sw = new Stopwatch(); // For benchmarking purposes we create an instance of a Stopwatch
                sw.Start();

                BigInteger rNplusOne = GenerateOTP(lastn + 1);

                for (int i = 0; i < 10; i++)
                {
                    byte[] sweetword = new byte[43];
                    Buffer.BlockCopy(sweetbytes, i * 43, sweetword, 0, 43);
                    ECPoint swd = SecNamedCurves.GetByName("sect163k1").Curve.DecodePoint(sweetword);
                    swd.Multiply(rNplusOne);
                    sweetword = swd.GetEncoded();

                    for (int j = 0; j < 43; j++) // Each sweetword has 43 bytes long, I hope :)
                    {
                        sweetbytes[i * 43 + j] = sweetword[j];
                    }
                }

                sw.Stop(); // We measure the time between sending a login request and receiving a response.

                Buffer.BlockCopy(sweetbytes, 0, data, 4, 430);

                using (SqlConnection con = new SqlConnection(connStr))
                {
                    con.Open();
                    using (SqlCommand cmd = new SqlCommand("UPDATE IndexTable SET n=@n WHERE Id=@id", con))
                    {
                        cmd.Parameters.AddWithValue("@n", lastn + 1);
                        cmd.Parameters.AddWithValue("@id", id);
                        cmd.ExecuteNonQuery();
                    }
                }

                client.Send(data, data.Length, SocketFlags.None);

                Console.WriteLine("Elapsed time: " + sw.Elapsed.TotalMilliseconds + " ms."); // This outputs the elapsed time.
                //Debug.WriteLine("Elapsed time: " + sw.Elapsed.TotalMilliseconds + " ms."); // This outputs the elapsed time.
            }
            Console.WriteLine("Disconnected from {0}", clientep.Address);
            client.Close();
            newsock.Close();
            Console.ReadKey();
        }
Пример #28
0
 private void Accept_Helper(IPAddress listenOn, IPAddress connectTo, int port)
 {
     using (Socket serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp))
     {
         serverSocket.Bind(new IPEndPoint(listenOn, port));
         serverSocket.Listen(1);
         SocketClient client = new SocketClient(serverSocket, connectTo, port);
         Socket clientSocket = serverSocket.Accept();
         Assert.True(clientSocket.Connected);
         Assert.True(clientSocket.DualMode);
         Assert.Equal(AddressFamily.InterNetworkV6, clientSocket.AddressFamily);
     }
 }
Пример #29
0
 private void WaitPlayer()
 {
     try { client = server.Accept(); }
     catch { return; }
     Invoke((Action)(() => Close()));
 }
Пример #30
0
        private void btnStart_Click(object sender, EventArgs e)
        {
            if (!startServer)
            {
                string path = Path.GetDirectoryName(Application.ExecutablePath);
                path = Path.Combine(path, Controller.Constant.nameFolderSaveFile);
                path = Path.Combine(path, Controller.Constant.nameFileSetting);

                if (File.Exists(path))
                {
                    Controller.IO_INI ini  = new Controller.IO_INI(path);
                    string            ip   = ini.IniReadValue(Controller.Constant.sectionInfo, Controller.Constant.keyIP);
                    string            port = ini.IniReadValue(Controller.Constant.sectionInfo, Controller.Constant.keyPort);

                    eventStartServer(this, new Controller.EventSendData(ip, port));

                    sckServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    try
                    {
                        sckServer.Bind(new IPEndPoint(IPAddress.Any, Convert.ToInt32(port)));
                        sckServer.Listen(100);
                        AppendText(txtCmd, "Server start. Waiting for client ..........", new Tuple <int, int, int>(165, 42, 42));
                    }
                    catch (SocketException ex)
                    {
                        MessageBox.Show(ex.ToString(), "Có lỗi xảy ra", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }

                    startServer = true;

                    Listening = new Thread(() =>
                    {
                        try
                        {
                            while (startServer)
                            {
                                Socket sckClient = sckServer.Accept();

                                Controller.ConnectionHandle server = new Controller.ConnectionHandle(sckClient, txtCmd);

                                server.Run();
                            }
                        }
                        catch (Exception ex)
                        {
                            //MessageBox.Show(ex.ToString(), "Thread", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    });
                    Listening.IsBackground = true;
                    Listening.Start();


                    btnStart.Visible = false;
                    btnStop.Visible  = true;
                }
                else
                {
                    MessageBox.Show("Không tìm thấy file " + Controller.Constant.nameFileSetting + "! Vui lòng kiểm tra lại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            else
            {
                AppendText(txtCmd, "Server was started!", new Tuple <int, int, int>(165, 42, 42));
            }
        }
Пример #31
0
        private void ServerAcceptThread()
        {
            running = true;

            DebugLog("Waiting for connections...");

            while (running)
            {
                try
                {
                    Socket newSocket = listeningSocket.Accept();

                    if (newSocket != null)
                    {
                        newSocket.NoDelay = true;

                        DebugLog("New connection");

                        IPEndPoint ipEndPoint = (IPEndPoint)newSocket.RemoteEndPoint;

                        DebugLog("  from IP: " + ipEndPoint.Address.ToString());


                        bool acceptConnection = true;

                        if (OpenConnections >= maxOpenConnections)
                        {
                            acceptConnection = false;
                        }

                        if (acceptConnection && (connectionRequestHandler != null))
                        {
                            acceptConnection = connectionRequestHandler(connectionRequestHandlerParameter, ipEndPoint.Address);
                        }

                        if (acceptConnection)
                        {
                            ClientConnection connection = null;

                            if ((serverMode == ServerMode.SINGLE_REDUNDANCY_GROUP) || (serverMode == ServerMode.MULTIPLE_REDUNDANCY_GROUPS))
                            {
                                RedundancyGroup catchAllGroup = null;

                                RedundancyGroup matchingGroup = null;

                                /* get matching redundancy group */
                                foreach (RedundancyGroup redGroup in redGroups)
                                {
                                    if (redGroup.Matches(ipEndPoint.Address))
                                    {
                                        matchingGroup = redGroup;
                                        break;
                                    }

                                    if (redGroup.IsCatchAll)
                                    {
                                        catchAllGroup = redGroup;
                                    }
                                }

                                if (matchingGroup == null)
                                {
                                    matchingGroup = catchAllGroup;
                                }

                                if (matchingGroup != null)
                                {
                                    connection = new ClientConnection(newSocket, securityInfo, apciParameters, alParameters, this,
                                                                      matchingGroup.asduQueue, debugOutput);

                                    matchingGroup.AddConnection(connection);

                                    DebugLog("Add connection to group " + matchingGroup.Name);
                                }
                                else
                                {
                                    DebugLog("Found no matching redundancy group -> close connection");
                                    newSocket.Close();
                                }
                            }
                            else
                            {
                                connection = new ClientConnection(newSocket, securityInfo, apciParameters, alParameters, this,
                                                                  new ASDUQueue(maxQueueSize, enqueueMode, alParameters, DebugLog), debugOutput);
                            }

                            if (connection != null)
                            {
                                allOpenConnections.Add(connection);

                                CallConnectionEventHandler(connection, ClientConnectionEvent.OPENED);
                            }
                        }
                        else
                        {
                            newSocket.Close();
                        }
                    }
                }
                catch (Exception)
                {
                    running = false;
                }
            }
        }
Пример #32
0
        private void Listener()
        {
            server1 = null;
            byte[] rcvBuffer_full    = new byte[BUFSIZE_FULL];
            byte[] rcvBuffer_partial = new byte[BUFSIZE];
            port_listen_int = System.Convert.ToInt16(textBox3.Text);
            using (server1 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                try
                {
                    server1.Bind(new IPEndPoint(IPAddress.Parse(textBox4.Text), port_listen_int));
                    server1.Listen(BACKLOG);
                    Debug("SERVER: socket <" + textBox4.Text + ":" + port_listen_int.ToString() + "> deschis");
                }
                catch (Exception ex)
                {
                    Debug("SERVER: probleme creare server socket <" + textBox4.Text + ":" + port_listen_int.ToString() + ">");
                    //Debug(ex.ToString());
                };
                while (true)
                {
                    client1      = null;
                    ClientIP_int = null;
                    int bytesRcvd = 0, totalBytesReceived = 0;
                    try
                    {
                        using (client1 = server1.Accept())
                        {
                            Debug("SERVER: client socket <" + client1.RemoteEndPoint.ToString() + "> conectat");
                            ClientIP_int = (client1.RemoteEndPoint.ToString()).Split(':')[0];
                            while ((bytesRcvd = client1.Receive(rcvBuffer_full, 0, rcvBuffer_full.Length, SocketFlags.None)) > 0)
                            {
                                if (totalBytesReceived >= rcvBuffer_full.Length)
                                {
                                    break;
                                }
                                ;
                                totalBytesReceived += bytesRcvd;
                            }
                            ;
                            Array.Copy(rcvBuffer_full, 4, rcvBuffer_partial, 0, totalBytesReceived - 4);
                            if (checkBox1.Checked)
                            {
                                switch (comboBox1.Text)
                                {
                                case "ASCII":
                                    if ((checkBox2.Checked) && (label11.Text != ""))
                                    {
                                        if (Validation(label11.Text))
                                        {
                                            richTextBox2.Text = Encoding.ASCII.GetString(rcvBuffer_partial, 0, (totalBytesReceived - 4));
                                        }
                                        else
                                        {
                                            Debug("SERVER: eroare parsare XML via schema inclusa in antet");
                                        };
                                    }
                                    else
                                    {
                                        richTextBox2.Text = Encoding.ASCII.GetString(rcvBuffer_partial, 0, (totalBytesReceived - 4));
                                    };
                                    break;

                                case "UTF7":
                                    if ((checkBox2.Checked) && (label11.Text != ""))
                                    {
                                        if (Validation(label11.Text))
                                        {
                                            richTextBox2.Text = Encoding.UTF7.GetString(rcvBuffer_partial, 0, (totalBytesReceived - 4));
                                        }
                                        else
                                        {
                                            Debug("SERVER: eroare parsare XML via schema inclusa in antet");
                                        };
                                    }
                                    else
                                    {
                                        richTextBox2.Text = Encoding.UTF7.GetString(rcvBuffer_partial, 0, (totalBytesReceived - 4));
                                    };
                                    break;

                                case "UTF8":
                                    if ((checkBox2.Checked) && (label11.Text != ""))
                                    {
                                        if (Validation(label11.Text))
                                        {
                                            richTextBox2.Text = Encoding.UTF8.GetString(rcvBuffer_partial, 0, (totalBytesReceived - 4));
                                        }
                                        else
                                        {
                                            Debug("SERVER: eroare parsare XML via schema inclusa in antet");
                                        };
                                    }
                                    else
                                    {
                                        richTextBox2.Text = Encoding.UTF8.GetString(rcvBuffer_partial, 0, (totalBytesReceived - 4));
                                    };
                                    break;

                                case "Unicode":
                                    if ((checkBox2.Checked) && (label11.Text != ""))
                                    {
                                        if (Validation(label11.Text))
                                        {
                                            richTextBox2.Text = Encoding.Unicode.GetString(rcvBuffer_partial, 0, (totalBytesReceived - 4));
                                        }
                                        else
                                        {
                                            Debug("SERVER: eroare parsare XML via schema inclusa in antet");
                                        };
                                    }
                                    else
                                    {
                                        richTextBox2.Text = Encoding.Unicode.GetString(rcvBuffer_partial, 0, (totalBytesReceived - 4));
                                    };
                                    break;

                                default:
                                    //
                                    break;
                                }
                                ;
                                Debug("SERVER: receptionat " + (totalBytesReceived - 4) + " bytes");
                                if (checkBox3.Checked)
                                {
                                    /*
                                     * client1.Send(rcvBuffer_partial, 0, rcvBuffer_partial.Length, SocketFlags.None);
                                     * Debug("SERVER: expediat echo data catre client.");
                                     */
                                }
                                ;
                            }
                            else
                            {
                                switch (comboBox1.Text)
                                {
                                case "ASCII":
                                    if ((checkBox2.Checked) && (label11.Text != ""))
                                    {
                                        if (Validation(label11.Text))
                                        {
                                            richTextBox2.Text = Encoding.ASCII.GetString(rcvBuffer_full, 0, totalBytesReceived);
                                        }
                                        else
                                        {
                                            Debug("SERVER: eroare parsare XML via schema inclusa in antet");
                                        };
                                    }
                                    else
                                    {
                                        richTextBox2.Text = Encoding.ASCII.GetString(rcvBuffer_full, 0, totalBytesReceived);
                                    };
                                    break;

                                case "UTF7":
                                    if ((checkBox2.Checked) && (label11.Text != ""))
                                    {
                                        if (Validation(label11.Text))
                                        {
                                            richTextBox2.Text = Encoding.UTF7.GetString(rcvBuffer_full, 0, totalBytesReceived);
                                        }
                                        else
                                        {
                                            Debug("SERVER: eroare parsare XML via schema inclusa in antet");
                                        };
                                    }
                                    else
                                    {
                                        richTextBox2.Text = Encoding.UTF7.GetString(rcvBuffer_full, 0, totalBytesReceived);
                                    };
                                    break;

                                case "UTF8":
                                    if ((checkBox2.Checked) && (label11.Text != ""))
                                    {
                                        if (Validation(label11.Text))
                                        {
                                            richTextBox2.Text = Encoding.UTF8.GetString(rcvBuffer_full, 0, totalBytesReceived);
                                        }
                                        else
                                        {
                                            Debug("SERVER: eroare parsare XML via schema inclusa in antet");
                                        };
                                    }
                                    else
                                    {
                                        richTextBox2.Text = Encoding.UTF8.GetString(rcvBuffer_full, 0, totalBytesReceived);
                                    };
                                    break;

                                case "Unicode":
                                    if ((checkBox2.Checked) && (label11.Text != ""))
                                    {
                                        if (Validation(label11.Text))
                                        {
                                            richTextBox2.Text = Encoding.Unicode.GetString(rcvBuffer_full, 0, totalBytesReceived);
                                        }
                                        else
                                        {
                                            Debug("SERVER: eroare parsare XML via schema inclusa in antet");
                                        };
                                    }
                                    else
                                    {
                                        richTextBox2.Text = Encoding.Unicode.GetString(rcvBuffer_full, 0, totalBytesReceived);
                                    };
                                    break;

                                default:
                                    //
                                    break;
                                }
                                ;
                                Debug("SERVER: receptionat " + totalBytesReceived + " bytes");
                                if (checkBox3.Checked)
                                {
                                    /*
                                     * client1.Send(rcvBuffer_partial, 0, rcvBuffer_partial.Length, SocketFlags.None);
                                     * Debug("SERVER: expediat echo data catre client.");
                                     */
                                }
                                ;
                            };
                        };
                        if (client1 != null)
                        {
                            client1.Close();
                        }
                        ;
                        Debug("SERVER: client socket deconectat");
                    }
                    catch (Exception ex)
                    {
                        //Debug(ex.ToString());
                    }
                    finally
                    {
                        if (client1 != null)
                        {
                            client1.Close();
                        }
                        ;
                    };
                }
                ;
            };
        }
        private void SpyServerListener()
        {
            while (true)
            {
                if (sSocket != null)
                {
                    try
                    {
                        Socket clientSocket = sSocket.Accept();
                        Logger.Info(string.Format("来自【{0}】新的指挥请示已接入!开启计时器!", clientSocket.RemoteEndPoint.ToString()));
                        //获得请求后,开启计时器,显示指挥时间。
                        speakTime.Elapsed += SpeakTime_Elapsed;
                        sw.Start();
                        speakTime.Start();
                        SetForm(false);
                        //计时器开启后,开始接收数据并播放。
                        while (true)
                        {
                            try
                            {
                                byte[] dataSize = RecerveVarData(clientSocket);
                                if (dataSize.Length <= 0)
                                {
                                    Logger.Info("无语音流,指挥结束!!!");
                                    speakTime.Stop();
                                    sw.Stop();
                                    sw.Reset();
                                    SetLB(string.Format("00:00:00"));
                                    SetForm(true);
                                    if (clientSocket != null)
                                    {
                                        //接收不到语音流,关闭套接字
                                        clientSocket.Shutdown(SocketShutdown.Both);
                                        clientSocket.Close();
                                        clientSocket.Dispose();
                                        clientSocket = null;
                                    }
                                    break;
                                }
                                else
                                {
                                    byte[] dec;
                                    ALawDecoder.ALawDecode(dataSize, dataSize.Length, out dec);
                                    var da = DataAvailable;
                                    if (da != null)
                                    {
                                        //Logger.Info("接受一段语音流,进入播放!!!");
                                        if (_sampleChannel != null)
                                        {
                                            _waveProvider.AddSamples(dec, 0, dec.Length);

                                            var sampleBuffer = new float[dec.Length];
                                            int read         = _sampleChannel.Read(sampleBuffer, 0, dec.Length);

                                            da(this, new DataAvailableEventArgs((byte[])dec.Clone(), read));

                                            if (Listening)
                                            {
                                                WaveOutProvider?.AddSamples(dec, 0, read);
                                            }
                                        }
                                    }
                                }
                            }
                            catch (SocketException se)
                            {
                                //sSocket.Shutdown(SocketShutdown.Both);
                                Logger.Error("通信出现异常,退出Socket. " + se.Message);
                                sSocket.Dispose();
                                sSocket = null;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        if (sSocket != null)
                        {
                            Logger.Error("通信出现异常,关闭Socket. " + e.Message);
                            //接收不到语音流,关闭套接字
                            sSocket.Close();
                            sSocket.Dispose();
                            sSocket = null;
                        }
                    }
                }
                else
                {
                    if (speakTime != null)
                    {
                        Logger.Error("指挥端通信结束,计时器停止。");
                        speakTime.Stop();
                    }
                    if (sw != null)
                    {
                        sw.Stop();
                    }

                    SetLB(string.Format("00:00:00"));
                    SetForm(true);

                    Logger.Info("ServerStream ReStart!!!");
                    Start();
                }
            }
        }
Пример #34
0
        /// <summary>
        /// 程序主循环
        /// </summary>
        /// <param name="args">输入变量</param>
        static void Main(string[] args)
        {
            // 检查环境
            if (!Functions.CheckEnvironment())
            {
                return;
            }
            Logger.HistoryPrinting(Logger.Level.INFO, MethodBase.GetCurrentMethod().DeclaringType.FullName, "Console msg server starts with successful checked.");

            // 创建Pipe通讯管道
            innerPipe = new NamedPipeServerStream("innerCommunication", PipeDirection.InOut, 1);

            // Pipe等待连接Task开启
            pipeConnectionTask = new Task(() => PipeConnectionTaskWork());
            pipeConnectionTask.Start();

            // 装上TCP心跳定时器
            tcpBeatClocker.AutoReset = false;
            tcpBeatClocker.Elapsed  += tcpBeatClocker_Elapsed;

            while (ifLoopContinue)
            {
                // 刷新公共密钥
                using (AesCryptoServiceProvider tempAes = new AesCryptoServiceProvider())
                {
                    tempAes.GenerateKey();
                    tempAes.GenerateIV();
                    commonKey = tempAes.Key;
                    commonIV  = tempAes.IV;
                }

                // TCP侦听socket建立 开始侦听
                tcpListenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                tcpListenSocket.Bind(new IPEndPoint(IPAddress.Parse(ifAtSamePC ? serverIPAtSamePC : serverIPAtDiffPC), serverPortTCPAny));
                tcpListenSocket.Listen(1);
                Logger.HistoryPrinting(Logger.Level.INFO, MethodBase.GetCurrentMethod().DeclaringType.FullName, "Console msg server tcp listener begins to listen.");

                // TCP侦听socket等待连接建立
                tcpTransferSocket = tcpListenSocket.Accept();
                tcpTransferSocket.ReceiveTimeout = tcpSocketRecieveTimeOut;
                tcpTransferSocket.SendTimeout    = tcpSocketSendTimeOut;
                Logger.HistoryPrinting(Logger.Level.INFO, MethodBase.GetCurrentMethod().DeclaringType.FullName, "Console msg server tcp transfer connection is established.");

                // TCP连接建立之后关闭侦听socket
                tcpListenSocket.Close();
                Logger.HistoryPrinting(Logger.Level.INFO, MethodBase.GetCurrentMethod().DeclaringType.FullName, "Console msg server tcp listener is closed.");

                // TCP侦听socket关闭后 开始允许TCP传输socket接收数据
                tcpRecieveCancel = new CancellationTokenSource();
                tcpRecieveTask   = new Task(() => TcpRecieveTaskWork(tcpRecieveCancel.Token));
                tcpRecieveTask.Start();

                // TCP侦听socket关闭后 开始允许TCP传输socket发送Buffer内数据
                tcpSendCancel = new CancellationTokenSource();
                tcpSendTask   = new Task(() => TcpSendTaskWork(tcpSendCancel.Token));
                tcpSendTask.Start();

                // 打开心跳定时器
                tcpBeatClocker.Start();
                Logger.HistoryPrinting(Logger.Level.INFO, MethodBase.GetCurrentMethod().DeclaringType.FullName, "Beats is required.");

                // 准备连接Pipe通讯
                if (!ifPipeTransferEstablished)           // 没连接Pipe则新建连接
                {
                    Process.Start(localUIProgramAddress); // 打开本地UI
                    while (!ifPipeTransferEstablished)
                    {
                        Thread.Sleep(1000);                                // 等待直到Pipe连接
                    }
                }

                // 等待直到TCP结束传输数据
                tcpRecieveTask.Wait();
                tcpSendTask.Wait();

                // 准备再次进行TCP监听
                FinishAllTCPConnection();

                // 等待后继续
                Thread.Sleep(1000);

                // 清空缓存区
                lock (pipeToTcpBufferLocker)
                {
                    pipeToTcpBuffer.Clear();
                }
                lock (tcpToPipeBufferLocker)
                {
                    tcpToPipeBuffer.Clear();
                }

                // 清空公钥密钥和设备号
                remoteDevicePublicKey = null;
                commonIV          = null;
                commonKey         = null;
                remoteDeviceIndex = null;

                // 等待后继续
                Thread.Sleep(1000);
            }

            Logger.HistoryPrinting(Logger.Level.INFO, MethodBase.GetCurrentMethod().DeclaringType.FullName, "Console msg server stops.");
        }
Пример #35
0
 private void ServerAgent()
 {
     while (!_serverTerminate)
         try
         {
             WIZnet_W5100.Enable(SPI.SPI_module.SPI1, (Cpu.Pin)FEZ_Pin.Digital.Di10, (Cpu.Pin)FEZ_Pin.Digital.Di7, true);
             NetworkInterface.EnableStaticIP(ServerAddress, ServerSubnet, ServerGateway, ServerMac);
             NetworkInterface.EnableStaticDns(ServerGateway);
             try
             {
                 ListenerClose( /*_listenerSocket == null*/ ); /*just to ensure tidiness*/
                 _listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                 try
                 {
                     IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, ServerPort);
                     _listenerSocket.Bind(endPoint);
                     _listenerSocket.Listen(1); /*blocks...*/
                     SessionClose( /*_sessionSocket == null*/ ); /*just to ensure tidiness*/
                     using (_sessionSocket = _listenerSocket.Accept()) /*using overkill, but what th' hey...*/
                         try
                         {
                             SignOfLifeStart( /*_signOfLifeTimer != null*/ );
                             try
                             {
                                 byte[] buffer = new byte[/*extra for safety*/ 2 * CommandDefinition.PacketSize];
                                 while (/*read OK?*/_sessionSocket.Receive(buffer, buffer.Length, SocketFlags.None) >= 1 /*blocks...*/)
                                 {
                                     CommandDefinition.CommandFormat command = new CommandDefinition.CommandFormat();
                                     command = command.Deserialize(buffer);
                                     ProcessCommand(command);
                                 }
                             }
                             catch { SendSignOfLife(uint.MaxValue - 4); }
                             finally { SignOfLifeStop( /*_signOfLifeTimer == null*/ ); }
                         }
                         catch { SendSignOfLife(uint.MaxValue -3); }
                         finally { SessionClose( /*_sessionSocket == null*/ ); }
                 }
                 catch { SendSignOfLife(uint.MaxValue - 2); }
                 finally { ListenerClose( /*_listenerSocket == null*/ ); }
             }
             catch { SendSignOfLife(uint.MaxValue - 1); }
             finally { WIZnet_W5100.ReintializeNetworking(); }
         }
         catch { SendSignOfLife(uint.MaxValue); }
         finally
         {
             Thread.Sleep(/*1s*/ 1000 /*ms*/ );
             Program.ResetBoard();
         }
 }
Пример #36
0
        private static void SendRecv_Stream_TCP(IPAddress listenAt, bool useMultipleBuffers)
        {
            const int BytesToSend = 123456;
            const int ListenBacklog = 1;
            const int LingerTime = 10;
            const int TestTimeout = 30000;

            var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            server.BindToAnonymousPort(listenAt);

            server.Listen(ListenBacklog);

            int bytesReceived = 0;
            var receivedChecksum = new Fletcher32();
            var serverThread = new Thread(() =>
            {
                using (server)
                {
                    Socket remote = server.Accept();
                    Assert.NotNull(remote);

                    using (remote)
                    {
                        if (!useMultipleBuffers)
                        {
                            var recvBuffer = new byte[256];
                            for (;;)
                            {
                                int received = remote.Receive(recvBuffer, 0, recvBuffer.Length, SocketFlags.None);
                                if (received == 0)
                                {
                                    break;
                                }

                                bytesReceived += received;
                                receivedChecksum.Add(recvBuffer, 0, received);
                            }
                        }
                        else
                        {
                            var recvBuffers = new List<ArraySegment<byte>> {
                                new ArraySegment<byte>(new byte[123]),
                                new ArraySegment<byte>(new byte[256], 2, 100),
                                new ArraySegment<byte>(new byte[1], 0, 0),
                                new ArraySegment<byte>(new byte[64], 9, 33)
                            };

                            for (;;)
                            {
                                int received = remote.Receive(recvBuffers, SocketFlags.None);
                                if (received == 0)
                                {
                                    break;
                                }

                                bytesReceived += received;
                                for (int i = 0, remaining = received; i < recvBuffers.Count && remaining > 0; i++)
                                {
                                    ArraySegment<byte> buffer = recvBuffers[i];
                                    int toAdd = Math.Min(buffer.Count, remaining);
                                    receivedChecksum.Add(buffer.Array, buffer.Offset, toAdd);
                                    remaining -= toAdd;
                                }
                            }
                        }
                    }
                }
            });
            serverThread.Start();

            EndPoint clientEndpoint = server.LocalEndPoint;
            var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            client.Connect(clientEndpoint);

            int bytesSent = 0;
            var sentChecksum = new Fletcher32();
            using (client)
            {
                var random = new Random();

                if (!useMultipleBuffers)
                {
                    var sendBuffer = new byte[512];
                    for (int sent = 0, remaining = BytesToSend; remaining > 0; remaining -= sent)
                    {
                        random.NextBytes(sendBuffer);

                        sent = client.Send(sendBuffer, 0, Math.Min(sendBuffer.Length, remaining), SocketFlags.None);
                        bytesSent += sent;
                        sentChecksum.Add(sendBuffer, 0, sent);
                    }
                }
                else
                {
                    var sendBuffers = new List<ArraySegment<byte>> {
                        new ArraySegment<byte>(new byte[23]),
                        new ArraySegment<byte>(new byte[256], 2, 100),
                        new ArraySegment<byte>(new byte[1], 0, 0),
                        new ArraySegment<byte>(new byte[64], 9, 9)
                    };

                    for (int sent = 0, toSend = BytesToSend; toSend > 0; toSend -= sent)
                    {
                        for (int i = 0; i < sendBuffers.Count; i++)
                        {
                            random.NextBytes(sendBuffers[i].Array);
                        }

                        sent = client.Send(sendBuffers, SocketFlags.None);

                        bytesSent += sent;
                        for (int i = 0, remaining = sent; i < sendBuffers.Count && remaining > 0; i++)
                        {
                            ArraySegment<byte> buffer = sendBuffers[i];
                            int toAdd = Math.Min(buffer.Count, remaining);
                            sentChecksum.Add(buffer.Array, buffer.Offset, toAdd);
                            remaining -= toAdd;
                        }
                    }
                }

                client.LingerState = new LingerOption(true, LingerTime);
            }

            Assert.True(serverThread.Join(TestTimeout), "Completed within allowed time");

            Assert.Equal(bytesSent, bytesReceived);
            Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
        }
Пример #37
0
        public static void StartListening()
        {
            // Data buffer for incoming data.
            byte[] bytes = new Byte[1024];

            // Establish the local endpoint for the socket.
            // Dns.GetHostName returns the name of the
            // host running the application.
            IPHostEntry ipHostInfo    = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress   ipAddress     = ipHostInfo.AddressList[0];
            IPEndPoint  localEndPoint = new IPEndPoint(ipAddress, 11000);

            // Create a TCP/IP socket.
            Socket listener = new Socket(ipAddress.AddressFamily,
                                         SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and
            // listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);

                // Start listening for connections.
                while (true)
                {
                    Console.WriteLine("Waiting for a connection...");
                    // Program is suspended while waiting for an incoming connection.
                    Socket handler = listener.Accept();
                    data = null;

                    // An incoming connection needs to be processed.
                    while (true)
                    {
                        bytes = new byte[1024];
                        int bytesRec = handler.Receive(bytes);
                        data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                        if (data.IndexOf("<EOF>") > -1)
                        {
                            break;
                        }
                    }

                    // Show the data on the console.
                    Console.WriteLine("Text received : {0}", data);

                    // Echo the data back to the client.
                    byte[] msg = Encoding.ASCII.GetBytes(data);

                    handler.Send(msg);
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("\nPress ENTER to continue...");
            Console.Read();
        }
Пример #38
0
    void Start()
    {
        startingPosition = transform.localPosition;
        x_auth_token = "{ TINDER AUTH TOKEN GOES HERE }";

        socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        Debug.Log(ipHostInfo);
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
        socket.Bind(localEndPoint);
        socket.Listen(1);

        handler = socket.Accept();
        handler.Blocking = false;
        set_new_picture();
    }
            public void StartListening()
            {
                // Data buffer for incoming data.
                byte[] bytes = new Byte[1024];

                // Establish the local endpoint for the socket.
                // Dns.GetHostName returns the name of the
                // host running the application.
                IPHostEntry ipHostInfo    = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress   ipAddress     = IPAddress.Parse("127.0.0.1");
                IPEndPoint  localEndPoint = new IPEndPoint(ipAddress, 2001);

                // Create a TCP/IP socket.
                Socket listener = new Socket(AddressFamily.InterNetwork,
                                             SocketType.Stream, ProtocolType.Tcp);

                // Bind the socket to the local endpoint and
                // listen for incoming connections.
                try
                {
                    listener.Bind(localEndPoint);
                    listener.Listen(10);

                    // Start listening for connections.
                    while (true)
                    {
                        System.Diagnostics.Debug.WriteLine("Waiting for a connection...");
                        // Program is suspended while waiting for an incoming connection.
                        Socket handler = listener.Accept();
                        data    = null;
                        message = null;
                        byte[] header = null;
                        bytes = new byte[1024];

                        // An incoming connection needs to be processed.
                        while (true)
                        {
                            int bytesRec;
                            if (header == null)
                            {
                                header   = new byte[1026];
                                bytesRec = handler.Receive(header);
                            }
                            bytesRec = handler.Receive(bytes);
                            data    += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                            message  = data.Replace('\0', ' ');
                            if (message.Split(' ').Length > 2)
                            {
                                break;
                            }
                        }

                        // Show the data on the console.
                        System.Diagnostics.Debug.WriteLine("Text received : {0}", message.Split('+').ElementAt(1));

                        if (data.Contains("DownloadCompleted"))
                        {
                            ClearResources();
                        }
                        else
                        {
                            // Echo the data back to the client.
                            StartAdaptation(message.Split('+').ElementAt(1).ToString());
                            byte[] msg = Encoding.ASCII.GetBytes(data);
                            msg.CopyTo(header, 2);

                            handler.Send(header, header.Length, 0);
                        }
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                    }
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine(e.ToString());
                }

                System.Diagnostics.Debug.WriteLine("\nPress ENTER to continue...");
                Console.Read();
            }
Пример #40
0
 public Socket Accept()
 {
     return(listenSocket.Accept());
 }
Пример #41
0
        void RunServer()
        {
            byte[] bytes = new Byte[1024];

            // Establish the local endpoint for the socket.
            // Dns.GetHostName returns the name of the
            // host running the application.
            IPAddress  ipAddress     = IPAddress.Parse("169.254.39.115");
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 1234);

            // Create a TCP/IP socket.
            Socket listener = new Socket(ipAddress.AddressFamily,
                                         SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and
            // listen for incoming connections.
            try
            {
                listener.Bind(localEndPoint);
                listener.Listen(10);

                // Start listening for connections.
                Console.WriteLine("Waiting for a connection...");
                // Program is suspended while waiting for an incoming connection.
                Socket handler = listener.Accept();
                while (_runServer)
                {
                    string data = null;

                    // An incoming connection needs to be processed.
                    while (true)
                    {
                        int bytesRec = handler.Receive(bytes);
                        data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                        if (data.IndexOf("\n") > -1)
                        {
                            break;
                        }
                    }

                    data = data.Replace("\n", "");
                    string time = Program.GetDateTimeDash();

                    string enque = data + "," + time;
                    queue.Enqueue(enque);
                    // Show the data on the console.
                    //Console.WriteLine("Text enqueued : {0}", enque);
                    Console.WriteLine("Text enqueued at: {0}", time);

                    // Send data length back to the client.
                    byte[] msg_length = Encoding.ASCII.GetBytes(data.Length.ToString() + '\n');
                    handler.Send(msg_length);
                }
                handler.Shutdown(SocketShutdown.Both);
                handler.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
Пример #42
0
 public IAppSocket Accept()
 {
     return(new AppSocket(_wrappedSocket?.Accept()));
 }
Пример #43
0
        public void StartListening()
        {
            IPEndPoint localEP = new IPEndPoint(IPAddress.Parse("200.143.8.148"), 11002);

            // IPEndPoint localEP = new IPEndPoint(IPAddress.Parse("192.168.1.210") ,11002);

            this.log.GravaLog("Local address and port: " + localEP.ToString(), this.log.LogOpName);

            Socket listener = new Socket(AddressFamily.InterNetwork,
                                         SocketType.Stream,
                                         ProtocolType.Tcp);


            Thread    t;
            ArrayList ListThread = new ArrayList();

            String data = null;
            Socket handler;

            try
            {
                listener.Bind(localEP);
                listener.Listen(10);

                byte[] bytes;
                int    bytesRec;

                while (true)
                {
                    bytes = new byte[5024];

                    // Recebe o Socket
                    handler = listener.Accept();

                    bytesRec = handler.Receive(bytes);
                    data     = Encoding.ASCII.GetString(bytes, 0, bytesRec);

                    if (data.IndexOf("SITE") > -1)                      //
                    {
                        // Criando a Thread que vai receber os dados da URA
                        t      = new Thread(new ThreadStart(TrataSocketUra));
                        t.Name = data;
                        t.Start();

                        ListThread.Add(t);

                        // Fechando o socket da URA
                        handler.Shutdown(SocketShutdown.Both);
                        handler.Close();
                    }
                    else if (data.IndexOf("FLASH") > -1)
                    {
                        flashGame = handler;

                        // Criando a Thread que vai receber os dados do FLASH
                        t          = new Thread(new ThreadStart(TrataSocketFlash));
                        t.Priority = ThreadPriority.Normal;
                        t.Start();

                        ListThread.Add(t);
                    }

                    // LogWriter.getLogWriter().GravaLog("Text received from socket: " + data,LogWriter.getLogWriter().LogOpName);

                    data = "";
                }
            }
            catch (Exception e)
            {
                this.log.GravaLog("Error:" + e.ToString(), this.log.LogErrorName);
            }
        }
Пример #44
0
        static void Main(string[] args)
        {
            // Lister: in ascolto quando si parla dei server
            // EndPoint: identifica una coppia IP/Porta

            //Creare il mio socketlistener
            //1) specifico che versione IP
            //2) tipo di socket. Stream.
            //3) protocollo a livello di trasporto
            Socket listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
                                               ProtocolType.Tcp);
            // config: IP dove ascoltare. Possiamo usare l'opzione Any: ascolta da tutte le interfaccie all'interno del mio pc.
            IPAddress ipaddr = IPAddress.Any;

            // config: devo configurare l'EndPoint
            IPEndPoint ipep = new IPEndPoint(ipaddr, 23000);

            // config: Bind -> collegamento
            // listenerSocket lo collego all'endpoint che ho appena configurato
            listenerSocket.Bind(ipep);

            // Mettere in ascolto il server.
            // parametro: il numero massimo di connessioni da mettere in coda.
            listenerSocket.Listen(5);
            while (true)
            {
                Console.WriteLine("Server in ascolto...");
                Console.WriteLine("in attesa di connessione da parte del client...");
                // Istruzione bloccante
                // restituisce una variabile di tipo socket.
                Socket client = listenerSocket.Accept();

                Console.WriteLine("Client IP: " + client.RemoteEndPoint.ToString());

                // mi attrezzo per ricevere un messaggio dal client
                // siccome è di tipo stream io riceverò dei byte, o meglio un byte array
                // riceverò anche il numero di byte.
                byte[] buff = new byte[128];
                int    receivedBytes = 0;
                int    sendedBytes = 0;
                string receivedString, sendString = "";



                while (true)
                {
                    receivedBytes = client.Receive(buff);
                    Console.WriteLine("Numero di byte ricevuti: " + receivedBytes);
                    receivedString = Encoding.ASCII.GetString(buff, 0, receivedBytes);
                    Console.WriteLine("Stringa ricevuta: " + receivedString);

                    if (receivedString != "\r\n")
                    {
                        if (receivedString.ToLower() == "quit")
                        {
                            Array.Clear(buff, 0, buff.Length);
                            sendedBytes = 0;

                            // crea il messaggio
                            sendString = "Arrivederci";

                            // lo converto in byte
                            buff = Encoding.ASCII.GetBytes(sendString);

                            //invio al client il messaggio
                            sendedBytes = client.Send(buff);
                            break;
                        }


                        switch (receivedString.ToLower())
                        {
                        case "ciao":
                            sendString = "Benvenuto su Pippo";
                            break;

                        case "come va?":
                            sendString = "Tutto bene grazie";
                            break;

                        case "che fai?":
                            sendString = "Ti ascolto per risponderti";
                            break;

                        case "chi mi ha programmato?":
                            sendString = "Il mio programmatore è stato Francesco Pippi";
                            break;

                        default:
                            sendString = "Non ho capito";
                            break;
                        }

                        Array.Clear(buff, 0, buff.Length);
                        sendedBytes = 0;
                        // lo converto in byte
                        buff = Encoding.ASCII.GetBytes(sendString + "\r\n");

                        //invio al client il messaggio
                        sendedBytes = client.Send(buff);
                    }
                    Array.Clear(buff, 0, buff.Length);
                }
            }
        }
Пример #45
0
 public ISocket Accept()
 {
     return(New(InternalSocket.Accept()));
 }
Пример #46
0
        public void CtorAndAccept_SocketNotKeptAliveViaInheritance(bool validateClientOuter, int acceptApiOuter)
        {
            // 300 ms should be long enough to connect if the socket is actually present & listening.
            const int ConnectionTimeoutMs = 300;

            // Run the test in another process so as to not have trouble with other tests
            // launching child processes that might impact inheritance.
            RemoteExecutor.Invoke((validateClientString, acceptApiString) =>
            {
                bool validateClient = bool.Parse(validateClientString);
                int acceptApi       = int.Parse(acceptApiString);

                // Create a listening server.
                using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                    listener.Listen();
                    EndPoint ep = listener.LocalEndPoint;

                    // Create a client and connect to that listener.
                    using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                    {
                        client.Connect(ep);

                        // Accept the connection using one of multiple accept mechanisms.
                        Socket server =
                            acceptApi == 0 ? listener.Accept() :
                            acceptApi == 1 ? listener.AcceptAsync().GetAwaiter().GetResult() :
                            acceptApi == 2 ? Task.Factory.FromAsync(listener.BeginAccept, listener.EndAccept, null).GetAwaiter().GetResult() :
                            throw new Exception($"Unexpected {nameof(acceptApi)}: {acceptApi}");

                        // Get streams for the client and server, and create a pipe that we'll use
                        // to communicate with a child process.
                        using (var serverStream = new NetworkStream(server, ownsSocket: true))
                            using (var clientStream = new NetworkStream(client, ownsSocket: true))
                                using (var serverPipe = new AnonymousPipeServerStream(PipeDirection.Out, HandleInheritability.Inheritable))
                                {
                                    // Create a child process that blocks waiting to receive a signal on the anonymous pipe.
                                    // The whole purpose of the child is to test whether handles are inherited, so we
                                    // keep the child process alive until we're done validating that handles close as expected.
                                    using (RemoteExecutor.Invoke(clientPipeHandle =>
                                    {
                                        using (var clientPipe = new AnonymousPipeClientStream(PipeDirection.In, clientPipeHandle))
                                        {
                                            Assert.Equal(42, clientPipe.ReadByte());
                                        }
                                    }, serverPipe.GetClientHandleAsString()))
                                    {
                                        if (validateClient) // Validate that the child isn't keeping alive the "new Socket" for the client
                                        {
                                            // Send data from the server to client, then validate the client gets EOF when the server closes.
                                            serverStream.WriteByte(84);
                                            Assert.Equal(84, clientStream.ReadByte());
                                            serverStream.Close();
                                            Assert.Equal(-1, clientStream.ReadByte());
                                        }
                                        else // Validate that the child isn't keeping alive the "listener.Accept" for the server
                                        {
                                            // Send data from the client to server, then validate the server gets EOF when the client closes.
                                            clientStream.WriteByte(84);
                                            Assert.Equal(84, serverStream.ReadByte());
                                            clientStream.Close();
                                            Assert.Equal(-1, serverStream.ReadByte());
                                        }

                                        // And validate that we after closing the listening socket, we're not able to connect.
                                        listener.Dispose();
                                        using (var tmpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                                        {
                                            bool connected = tmpClient.TryConnect(ep, ConnectionTimeoutMs);

                                            // Let the child process terminate.
                                            serverPipe.WriteByte(42);

                                            Assert.False(connected);
                                        }
                                    }
                                }
                    }
                }
            }, validateClientOuter.ToString(), acceptApiOuter.ToString()).Dispose();
        }
Пример #47
0
        public bool StartServer()
        {
            try {
                IPEndPoint localEndpoint = new IPEndPoint(IPAddress.Any, Config.TCPServerPort);
                string     externalip    = new WebClient().DownloadString("https://api.ipify.org/").Trim('\n');
                Logger.Log("Public ip fetched sucessfully => " + externalip, Enums.LogLevels.Trace);
                Logger.Log("Local ip => " + Helpers.GetLocalIpAddress(), Enums.LogLevels.Trace);
                Logger.Log("Starting assistant command server...", Enums.LogLevels.Trace);
                Sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Logger.Log("Server started sucessfully on address: " + externalip + ":" + Config.TCPServerPort);

                Sock.Bind(localEndpoint);
                Sock.Listen(15);
                ServerOn = true;
                Logger.Log("Listerning for connections...");
                int errorCounter = 0;

                Helpers.InBackgroundThread(() => {
                    while (true)
                    {
                        try {
                            if (Sock != null)
                            {
                                Socket Socket   = Sock?.Accept();
                                int b           = Socket.Receive(Buffer);
                                EndPoint ep     = Socket.RemoteEndPoint;
                                string[] IpData = ep.ToString().Split(':');
                                string clientIP = IpData[0].Trim();
                                Logger.Log("Client IP: " + clientIP, Enums.LogLevels.Trace);

                                if (File.Exists(Constants.IPBlacklistPath) && File.ReadAllLines(Constants.IPBlacklistPath).Any(x => x.Equals(clientIP)))
                                {
                                    Logger.Log("Unauthorized IP Connected: " + clientIP, Enums.LogLevels.Error);
                                    Socket.Close();
                                }

                                ReceivedData = Encoding.ASCII.GetString(Buffer, 0, b);
                                Logger.Log($"Client Connected > {clientIP} > {ReceivedData}", Enums.LogLevels.Trace);
                                string resultText = OnRecevied(ReceivedData).Result;

                                if (resultText != null)
                                {
                                    byte[] Message = Encoding.ASCII.GetBytes(resultText);
                                    Socket.Send(Message);
                                }
                                else
                                {
                                    byte[] Message = Encoding.ASCII.GetBytes("Bad Command!");
                                    Socket.Send(Message);
                                }

                                Socket.Close();
                            }

                            Logger.Log("Client Disconnected.", Enums.LogLevels.Trace);

                            if (!ServerOn)
                            {
                                Helpers.ScheduleTask(() => {
                                    StopServer();
                                    StartServer();
                                }, TimeSpan.FromMinutes(1));
                                Logger.Log("Restarting server in 1 minute as it went offline.");
                                return;
                            }
                        }
                        catch (SocketException se) {
                            Logger.Log(se.Message, Enums.LogLevels.Trace);
                            errorCounter++;

                            if (errorCounter > 5)
                            {
                                Logger.Log("too many errors occured on TCP Server. stopping...", Enums.LogLevels.Error);
                                StopServer();
                            }

                            if (Sock != null)
                            {
                                StopServer();
                                if (!ServerOn)
                                {
                                    Helpers.ScheduleTask(() => {
                                        StopServer();
                                        StartServer();
                                    }, TimeSpan.FromMinutes(1));
                                    Logger.Log("Restarting server in 1 minute as it went offline.");
                                    return;
                                }
                            }
                        }
                        catch (InvalidOperationException ioe) {
                            Logger.Log(ioe.Message, Enums.LogLevels.Error);
                            errorCounter++;
                            if (errorCounter > 5)
                            {
                                Logger.Log("too many errors occured on TCP Server. stopping...", Enums.LogLevels.Error);
                                StopServer();
                            }
                        }
                    }
                }, "TCP Server", true);
            }
            catch (IOException io) {
                Logger.Log(io.Message, Enums.LogLevels.Error);
            }
            catch (FormatException fe) {
                Logger.Log(fe.Message, Enums.LogLevels.Error);
            }
            catch (IndexOutOfRangeException ioore) {
                Logger.Log(ioore.Message, Enums.LogLevels.Error);
            }
            catch (SocketException se) {
                Logger.Log(se.Message, Enums.LogLevels.Error);
                Helpers.ScheduleTask(() => {
                    StartServer();
                }, TimeSpan.FromMinutes(1));
                Logger.Log("Restarting server in 1 minute as it went offline.");
            }
            return(true);
        }
Пример #48
0
        //线程函数,封装一个建立连接的通信套接字
        private void StartListen()
        {
            isListen = true;
            //default()只是设置为一个初始值,这里应该为null
            Socket clientSocket = default(Socket);

            while (isListen)
            {
                try
                {
                    //  int accept(int sockfd, void *addr, int *addrlen);
                    //注意这个serverSocket,它是用来监听的套接字,当有用户连接上端口后会返回一个新的套接字也就是这里的clientSocket,sercerSocket还是在那儿继续监听的
                    //返回值是一个新的套接字描述符,它代表的是和客户端的新的连接,这个socket相当于一个客户端的socket,包含的是客户端的ip和port
                    //但是它也继承字本地的监听套接字,因此它也有服务器的ip和port信息
                    if (serverSocket == null)   //如果服务停止,即serverSocket为空了,那就直接返回
                    {
                        return;
                    }
                    clientSocket = serverSocket.Accept();   //这个方法返回一个通信套接字,并用这个套接字进行通信,错误时返回-1并设置全局错误变量
                }
                catch (SocketException e)
                {
                    File.AppendAllText("E:\\Exception.txt", e.ToString() + "\r\nStartListen\r\n" + DateTime.Now.ToString() + "\r\n");
                }

                //TCP是面向字节流的
                Byte[] bytesFrom      = new Byte[4096];
                String dataFromClient = null;

                if (clientSocket != null && clientSocket.Connected)
                {
                    try
                    {
                        //public int Receive(  byte[] buffer,  int offset,   int size,  SocketFlags socketFlags )
                        //buffer  是byte类型的数组,存储收到的数据的位置
                        //offset  是buffer中存储所接收数据的位置
                        //size    要接收的字节数
                        //socketFlags  socketFlages值的按位组合

                        Int32 len = clientSocket.Receive(bytesFrom);    //获取客户端发来的信息,返回的就是收到的字节数,并且把收到的信息都放在bytesForm里面

                        if (len > -1)
                        {
                            String tmp = Encoding.UTF8.GetString(bytesFrom, 0, len);  //将字节流转换成字符串

                            /*try
                             * {
                             *  dataFromClient = EncryptionAndDecryption.TripleDESDecrypting(tmp);      //数据加密传输
                             * }
                             * catch (Exception e)
                             * {
                             *
                             * }
                             * catch (Exception e)
                             * {
                             *
                             * }*/
                            dataFromClient = tmp;
                            Int32 sublen = dataFromClient.LastIndexOf("$");
                            if (sublen > -1)
                            {
                                dataFromClient = dataFromClient.Substring(0, sublen);   //获取用户名

                                if (!clientList.ContainsKey(dataFromClient))
                                {
                                    clientList.Add(dataFromClient, clientSocket);   //如果用户名不存在,则添加用户名进去

                                    //BroadCast是下面自己定义的一个类,是用来将消息对所有用户进行推送的
                                    //PushMessage(String msg, String uName, Boolean flag, Dictionary<String, Socket> clientList)
                                    BroadCast.PushMessage(dataFromClient + "Joined", dataFromClient, false, clientList);

                                    //HandleClient也是一个自己定义的类,用来负责接收客户端发来的消息并转发给所有的客户端
                                    //StartClient(Socket inClientSocket, String clientNo, Dictionary<String, Socket> cList)
                                    HandleClient client = new HandleClient(txtMsg);

                                    client.StartClient(clientSocket, dataFromClient, clientList);

                                    txtMsg.BeginInvoke(new Action(() =>
                                    {
                                        txtMsg.Text += dataFromClient + "连接上了服务器\r" + DateTime.Now + "\r\n";
                                    }));
                                }
                                else
                                {
                                    //用户名已经存在
                                    clientSocket.Send(Encoding.UTF8.GetBytes("#" + dataFromClient + "#"));
                                }
                            }
                        }
                    }
                    catch (Exception ep)
                    {
                        File.AppendAllText("E:\\Exception.txt", ep.ToString() + "\r\n\t\t" + DateTime.Now.ToString() + "\r\n");
                    }
                }
            }
        }
Пример #49
0
        static void Main(string[] args)
        {
            ServeurUdp.ServeurUdp.StartChat();

            Tron.Tron myTron;      // Moteur du jeu

            byte nJoueurs  = 2;    // Nombre de joueurs
            byte frequence = 1;    // Temps du tour de jeu (en dixieme de s)
            byte taille    = 60;   // Taille du terrain

            // ************************************* Intitialisation partie
            System.Console.WriteLine("Initialisation");

            // TODO Creation de la socket d'écoute TCP
            Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // TODO Bind et listen
            serverSocket.Bind(new IPEndPoint(IPAddress.Any, 23232));
            serverSocket.Listen(nJoueurs);
            while (1 == 1)
            {
                // TODO Creation du tableau des sockets connectées
                List <Socket> clients = new List <Socket>();

                // Creation du moteur de jeu
                myTron = new Tron.Tron(nJoueurs, taille);

                // TODO Acceptation des clients
                for (int i = 0; i < nJoueurs; i++)
                {
                    clients.Add(serverSocket.Accept());
                    Console.WriteLine("Connexion de " + clients[i].RemoteEndPoint);
                }

                // TODO Envoie des paramètres

                byte[] parametres = new byte[4];
                parametres[1] = nJoueurs;
                parametres[2] = frequence;
                parametres[3] = taille;

                for (int i = 0; i < nJoueurs; i++)
                {
                    parametres[0] = (byte)i;
                    clients[i].Send(parametres, parametres.Length, SocketFlags.None);
                }

                // ************************************* Routine à chaque tour
                System.Console.WriteLine("Routine");

                // Tant que la partie n'est pas finie
                while (!myTron.IsFinished())
                {
                    // TODO Réception de la direction de chaque joueur
                    byte[] directions = new byte[clients.Count];
                    byte[] receive    = new byte[1];
                    for (int i = 0; i < clients.Count; i++)
                    {
                        try
                        {
                            if (clients[i].Connected)
                            {
                                clients[i].Receive(receive, receive.Length, SocketFlags.None);
                                directions[i] = receive[0];
                            }
                            else
                            {
                                clients[i].Close();
                                // Perdu
                                directions[i] = 5;
                            }
                        }
                        catch (Exception e)
                        {
                            clients[i].Close();
                            // Perdu
                            directions[i] = 5;
                        }
                    }
                    // TODO Calcul collision : myTron.Collision(byte[] <toutes les directions>);

                    myTron.Collision(directions);

                    // TODO Envoie des directions de tous les joueurs à tous les clients

                    foreach (Socket s in clients)
                    {
                        try
                        {
                            if (s.Connected)
                            {
                                s.Send(directions, directions.Length, SocketFlags.None);
                            }
                        }
                        catch (Exception e)
                        {
                        }
                    }
                }


                // ************************************* Conclusion
                System.Console.WriteLine("Conclusion");

                // TODO Fermeture des sockets connectées

                foreach (Socket s in clients)
                {
                    if (s.Connected)
                    {
                        s.Close();
                    }
                }
            }
            // TODO Fermeture socket d'écoute
            serverSocket.Close();
            ServeurUdp.ServeurUdp.thread.Abort();
        }
Пример #50
0
 public override Task <Socket> AcceptAsync(Socket s) =>
 Task.Run(() => { Socket accepted = s.Accept(); accepted.ForceNonBlocking(true); return(accepted); });
Пример #51
0
        private static void Main(string[] args)
        {
            HandleFallbackArgs(ref args);

            var(localPort, backupPort) = ParseLocalPorts(args);

            lock (Mutex)
            {
                _pathBuilder = new FilePathBuilder($"fs{localPort}_");
            }

            if (TryParseRemoteBackupAddress(args, out var remoteBackupIp, out var remoteBackupPort))
            {
                HandleBackup(localPort, remoteBackupIp, remoteBackupPort);
            }

            lock (Mutex)
            {
                new BackupWorker(Mutex, () => _lastTree, _pathBuilder, () => _timestamp).LaunchOn(backupPort);
            }

            var ip    = IpAddressUtils.GetLocal();
            var local = new IPEndPoint(ip, localPort);

            using var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
            socket.Bind(local);

            Console.WriteLine($"File server is listening on {local}.");
            socket.Listen(1);
            using var client = socket.Accept();

            var buffer = new byte[32000];

            while (true)
            {
                var command = client.ReceiveUntilEof(buffer).To <ICommand>();
                Console.WriteLine($"Received {command}.");

                lock (Mutex)
                {
                    var statefulCommand = command as StatefulCommand;
                    if (statefulCommand != null)
                    {
                        _lastTree = statefulCommand.Root;
                    }

                    if (_lastTree == null)
                    {
                        continue;
                    }

                    Console.WriteLine(_lastTree);

                    var visitor = new CommandHandleVisitor(_lastTree, _pathBuilder);
                    command.Accept(visitor);
                    Console.WriteLine($"Handled {command}.");

                    ICommand response = visitor.Payload != null
                                                ? new PayloadResponseCommand(command, visitor.Payload, visitor.PayloadPath, _lastTree, _timestamp)
                                                : new ResponseCommand(command);
                    client.SendCompletelyWithEof(response.ToBytes());

                    if (statefulCommand != null && _timestamp.Value >= statefulCommand.Timestamp.Value - 1)
                    {
                        _timestamp = statefulCommand.Timestamp;
                    }

                    Console.WriteLine($"Sent {response}.");
                }
            }
        }
Пример #52
0
        static void Main(string[] args)
        {
            double p = 3, q = 7;
            double a = 2;
            double y;

            y = Math.Pow(p, a);
            y = y % q;
            int    i  = 1;
            Socket sk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //sk.GetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress);
            IPEndPoint io = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12331);

            sk.Connect(io);
            //Socket ac = sk.Accept();
            Byte[] buff = new byte[2147480];
            int    rece = sk.Receive(buff, 0, buff.Length, 0);

            Array.Resize(ref buff, rece);
            Console.WriteLine(Encoding.Default.GetString(buff));
            sk.Close();
            Socket     Sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1266);

            Sck.Bind(ipe);
            Sck.Listen(10);
            Socket     Sck2 = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint ipe2 = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1267);

            Sck2.Bind(ipe2);
            Sck2.Listen(10);
            string str, str1, str2;

            str1 = null;
            str2 = null;
            //str = Console.ReadLine();
            string stro = Encoding.Default.GetString(buff);

            foreach (char c in stro)
            {
                i++;
                if (i % 2 == 0)
                {
                    str1 = str1 + c;
                }
                else
                {
                    str2 = str2 + c;
                }
            }

            Socket acp = Sck.Accept();

            byte[] buffer = Encoding.Default.GetBytes(str1);

            acp.Send(buffer, 0, buffer.Length, 0);
            //byte[] buffer3 = Encoding.Default.GetBytes(str1);
            //acp.Send(buffer3, 0, buffer3.Length, 0);
            //buffer = new byte[255];
            //int rec = acp.Receive(buffer, 0, buffer.Length, 0);
            //Array.Resize(ref buffer, rec);
            //Console.WriteLine(Encoding.Default.GetString(buffer));
            Sck.Close();
            acp.Close();

            Socket acp2 = Sck2.Accept();

            byte[] buffer2 = Encoding.Default.GetBytes(str2);

            acp2.Send(buffer2, 0, buffer2.Length, 0);
            buffer2 = new byte[25510];
            //int rec2 = acp2.Receive(buffer2, 0, buffer2.Length, 0);
            //Array.Resize(ref buffer2, rec2);
            //Console.WriteLine(Encoding.Default.GetString(buffer2));
            Sck.Close();
            acp.Close();
            Console.Read();
            //
        }
Пример #53
0
    static void Main(string[] args)
    {
        int threadCount = 0;

        try
        {
            int port = 13000;
            IPAddress address = IPAddress.Parse("127.0.0.1");

            // IPAddress address = IPAddress.Parse("142.232.246.23");

            IPEndPoint ipe = new IPEndPoint(address, port);
            Socket s = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            s.Bind(ipe);
            s.Listen(10);

            while(true)
            {
                Socket cls = s.Accept();

                threadCount++;
                ClientHandler ch = new ClientHandler(cls, threadCount);
                Thread t = new Thread(new ThreadStart(ch.Handler));
                t.Start();
            }

            s.Close();
        }
        catch (SocketException e)
        {
            Console.WriteLine("Socket exception: {0}", e);
        }

        Console.Read();
    }
Пример #54
0
        public static void StartListening(HeepDevice device)
        {
            // Data buffer for incoming data.
            byte[] bytes = new Byte[1024];

            byte []    IPAddrArray   = { 0, 0, 0, 0 };
            IPAddress  theAddr       = new IPAddress(IPAddrArray);
            IPEndPoint localEndPoint = new IPEndPoint(theAddr, 5000);

            // Create a TCP/IP socket.
            Socket listener = new Socket(AddressFamily.InterNetwork,
                                         SocketType.Stream, ProtocolType.Tcp);

            // Bind the socket to the local endpoint and
            // listen for incoming connections.
            try {
                listener.Bind(localEndPoint);
                listener.Listen(10);

                // Start listening for connections.
                while (true)
                {
                    Console.WriteLine("Waiting for a connection...");
                    // Program is suspended while waiting for an incoming connection.
                    Socket handler = listener.Accept();

                    Console.WriteLine("Data accepted");

                    data = null;

                    bytes = new byte[1024];
                    int bytesRec = handler.Receive(bytes);
                    Console.WriteLine(bytesRec);
                    data += Encoding.ASCII.GetString(bytes, 0, bytesRec);

                    // Show the data on the console.
                    Console.WriteLine("Text received : {0}", data);

                    List <byte> commandData = new List <byte> ();
                    for (int i = 0; i < bytesRec; i++)
                    {
                        commandData.Add(bytes[i]);
                    }

                    // Echo the data back to the client.
//					byte[] msg = Encoding.ASCII.GetBytes(data);
                    List <byte> fromparser = HeepParser.ParseCommand(commandData, device);
                    byte[]      msg        = new byte[fromparser.Count];

                    for (int i = 0; i < fromparser.Count; i++)
                    {
                        msg[i] = fromparser[i];
                    }


                    handler.Send(msg);
                    handler.Shutdown(SocketShutdown.Both);
                    handler.Close();
                }
            } catch (Exception e) {
                Console.WriteLine(e.ToString());
            }

            Console.WriteLine("\nPress ENTER to continue...");
            Console.Read();
        }
Пример #55
0
 public void Accept_NotListening_Throws_InvalidOperation()
 {
     using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
     {
         socket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
         Assert.Throws<InvalidOperationException>(() => socket.Accept());
     }
 }
Пример #56
0
        void OpenDataConnection()
        {
            FtpStatus status;

            Socket s = InitDataConnection();

            // Handle content offset
            if (offset > 0)
            {
                status = SendCommand(RestCommand, offset.ToString());
                if (status.StatusCode != FtpStatusCode.FileCommandPending)
                {
                    throw CreateExceptionFromResponse(status);
                }
            }

            if (method != WebRequestMethods.Ftp.ListDirectory && method != WebRequestMethods.Ftp.ListDirectoryDetails &&
                method != WebRequestMethods.Ftp.UploadFileWithUniqueName)
            {
                status = SendCommand(method, file_name);
            }
            else
            {
                status = SendCommand(method);
            }

            if (status.StatusCode != FtpStatusCode.OpeningData && status.StatusCode != FtpStatusCode.DataAlreadyOpen)
            {
                throw CreateExceptionFromResponse(status);
            }

            if (usePassive)
            {
                origDataStream = new NetworkStream(s, true);
                dataStream     = origDataStream;
                if (EnableSsl)
                {
                    ChangeToSSLSocket(ref dataStream);
                }
            }
            else
            {
                // Active connection (use Socket.Blocking to true)
                Socket incoming = null;
                try {
                    incoming = s.Accept();
                }
                catch (SocketException) {
                    s.Close();
                    if (incoming != null)
                    {
                        incoming.Close();
                    }

                    throw new ProtocolViolationException("Server commited a protocol violation.");
                }

                s.Close();
                origDataStream = new NetworkStream(incoming, true);
                dataStream     = origDataStream;
                if (EnableSsl)
                {
                    ChangeToSSLSocket(ref dataStream);
                }
            }

            ftpResponse.UpdateStatus(status);
        }
	public static void Server()
	{
		//Find own local IP address
		IPHostEntry host;
		string localIP = "";
		host = Dns.GetHostEntry(Dns.GetHostName());
		foreach (IPAddress ip in host.AddressList)
		{
			if (ip.AddressFamily == AddressFamily.InterNetwork)
			{
				localIP = ip.ToString();
				break;
			}
		}
		
		
		int listenPort;



			listenPort = 137;

		int recv;
		IPEndPoint ipep;
		byte[] data = new byte[1024];
		byte[] msg = new byte[1024];
		string stMsg;
		try
		{
			ipep = new IPEndPoint(IPAddress.Any, listenPort);
		}
		catch
		{
			UnityEngine.Debug.Log("An error occured on that port. Using port 137 as default.");
			ipep = new IPEndPoint(IPAddress.Any, 137);
		}
		
		
		
		Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		
		newsock.Bind(ipep);
		newsock.Listen(10);
		UnityEngine.Debug.Log("Waiting for client....");

		Socket client = newsock.Accept();
		IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
		
		UnityEngine.Debug.Log("Connected with  at port "+ clientep.Address+ clientep.Port);
		
		string Welcome = "YOU ARE CONNECTED";
		string info = "Connected with  at port "+ clientep.Address+ clientep.Port;
		data = Encoding.ASCII.GetBytes(Welcome);
		client.Send(data, data.Length, SocketFlags.None);
		data = Encoding.ASCII.GetBytes (info);
		client.Send(data, data.Length, SocketFlags.None);
		int i = 0;
		while (true)
		{ i = i+1;
			data = new byte[1024];
			try
			{
				recv = client.Receive(data);
				if (recv == 0)
					break;
			}
			catch
			{
				break;
			}
			
			
			UnityEngine.Debug.Log(clientep.Address+": "+Encoding.ASCII.GetString(data, 0, recv));
			UnityEngine.Debug.Log(localIP + ": ");
			
			msg = new byte[1024];
			stMsg = "Server Side: " + i;
			msg = Encoding.ASCII.GetBytes(stMsg);
			if (i == 5)
			{

				msg.Equals( "Closing connection.");
			client.Send(msg, msg.Length, SocketFlags.None);
				break;
			}
			else
			{

				client.Send(msg, msg.Length, SocketFlags.None);
			}
		}
		
		UnityEngine.Debug.Log("Disconnected from client " + clientep.Address);
		
		client.Close();
		newsock.Close();
		
	}
Пример #58
0
        /// <summary>
        /// Accepts a bound listener and begins serving on its port. This method blocks.
        /// </summary>
        /// <param name="listener"></param>
        /// <param name="processResponseCallback"></param>
        /// <param name="processRequestBodyCallback"></param>
        /// <example>
        /// var listener = new Socket(SocketType.Stream, ProtocolType.Tcp);
        /// var endPoint = new IPEndPoint(IPAddress.Any,8080));
        /// listener.Bind(endPoint);
        /// listener.Listen(10);
        /// ThreadPool.QueueUserWorkItem((l) => {
        ///		listener.ServeHttp((request, response) => {
        ///				response.WriteLine("Hello World!");
        ///			});
        ///	}, listener);
        ///	// execute wait here as the above doesn't block
        /// </example>
        public static void ServeHttp(this Socket listener, ProcessResponse processResponseCallback, ProcessRequestBody processRequestBodyCallback = null)
        {
            var done = false;

            while (!done)
            {
                HttpRequest hreq   = null;
                Socket      socket = null;
                try
                {
                    socket = listener.Accept();
                }
                catch (SocketException)
                {
                    socket = null;
                }
                catch (ObjectDisposedException)
                {
                    socket = null;
                }
                if (null != socket)
                {
                    var t = socket.ReceiveHttpRequestAsync();
                    t.Wait();                     // sleep the thread until i/o arrives.
                    var newHreq = t.Result;
                    if (null != newHreq)
                    {
                        hreq = newHreq;
                    }
                    else
                    {
                        done = true;
                    }
                    if (null != hreq)
                    {
                        var hres = new HttpResponse(hreq, socket);
                        processResponseCallback(hreq, hres);
                        if (!hres.IsClosed)
                        {
                            if (!hres.HasSentHeaders)
                            {
                                hres.SendHeaders();
                            }
                            try
                            {
                                hres.SendEndChunk();
                            }
                            catch { }

                            if (!hres.HasHeader("Connection") && !hres.IsKeepAlive)
                            {
                                hres.Close();
                                done = true;
                            }
                        }
                        else
                        {
                            done = true;
                        }
                    }
                    else
                    {
                        done = true;
                    }
                }
                else
                {
                    done = true;
                }
            }
        }
Пример #59
0
 private void Accept_Helper(IPAddress listenOn, IPAddress connectTo)
 {
     using (Socket serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp))
     {
         int port = serverSocket.BindToAnonymousPort(listenOn);
         serverSocket.Listen(1);
         SocketClient client = new SocketClient(_log, serverSocket, connectTo, port);
         Socket clientSocket = serverSocket.Accept();
         Assert.True(clientSocket.Connected);
         AssertDualModeEnabled(clientSocket, listenOn);
         Assert.Equal(AddressFamily.InterNetworkV6, clientSocket.AddressFamily);
     }
 }
Пример #60
0
        public static void ExecuteServer()
        {
            // Establish the local endpoint
            // for the socket. Dns.GetHostName
            // returns the name of the host
            // running the application.
            IPHostEntry ipHost        = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress   ipAddr        = ipHost.AddressList[0];
            IPEndPoint  localEndPoint = new IPEndPoint(ipAddr, 11111);

            // Creation TCP/IP Socket using
            // Socket Class Costructor
            Socket listener = new Socket(ipAddr.AddressFamily,
                                         SocketType.Stream, ProtocolType.Tcp);

            try
            {
                // Using Bind() method we associate a
                // network address to the Server Socket
                // All client that will connect to this
                // Server Socket must know this network
                // Address
                listener.Bind(localEndPoint);

                // Using Listen() method we create
                // the Client list that will want
                // to connect to Server
                listener.Listen(10);

                while (true)
                {
                    Console.WriteLine("Waiting connection ... ");

                    // Suspend while waiting for
                    // incoming connection Using
                    // Accept() method the server
                    // will accept connection of client
                    Socket clientSocket = listener.Accept();

                    // Data buffer
                    byte[] bytes = new Byte[1024];
                    string data  = null;

                    while (true)
                    {
                        int numByte = clientSocket.Receive(bytes);

                        data += Encoding.ASCII.GetString(bytes,
                                                         0, numByte);

                        if (data.IndexOf("<EOF>") > -1)
                        {
                            break;
                        }
                    }

                    Console.WriteLine("Text received -> {0} ", data);
                    byte[] message = Encoding.ASCII.GetBytes("Test Server");

                    // Send a message to Client
                    // using Send() method
                    clientSocket.Send(message);

                    // Close client Socket using the
                    // Close() method. After closing,
                    // we can use the closed Socket
                    // for a new Client Connection
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.Close();
                }
            }

            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }