Esempio n. 1
1
    public bool CreateTcpServer(string ip, int listenPort)
    {
        _port = listenPort;
        _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        foreach (IPAddress address in Dns.GetHostEntry(ip).AddressList)
        {
            try
            {
                IPAddress hostIP = address;
                IPEndPoint ipe = new IPEndPoint(address, _port);

                _listener.Bind(ipe);
                _listener.Listen(_maxConnections);
                _listener.BeginAccept(new System.AsyncCallback(ListenTcpClient), _listener);

                break;

            }
            catch (System.Exception)
            {
                return false;
            }
        }

        return true;
    }
 public static void Wrong2()
 {
     var socket = new Socket();
     socket.Bind(new EndPoint());
     socket.Listen(1000);
     socket.Bind(new EndPoint());
     // Called Bind more than once.
 }
Esempio n. 3
0
	void Awake ()
	{                
        /*
#if UNITY_STANDALONE_WIN || UNITY_EDITOR_WIN
        objPath = "file://" + Application.streamingAssetsPath + "/model2.obj";
#else
#if UNITY_ANDROID
        FileInfo fi = new FileInfo("/sdcard/model.obj");
        if (fi.Exists)
            objPath = "file://" +"/sdcard/model.obj";
        else
            objPath = Application.streamingAssetsPath + "/model2.obj";            
#endif
#endif
         */
#if STANDALONE_DEBUG
        IPAddress ip = IPAddress.Parse("127.0.0.1");
        serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        serverSocket.Bind(new IPEndPoint(ip, myPort));
        serverSocket.Listen(5);
        clientSocket = new List<Socket>();
#endif
        load_state = LoadState.IDLE;
        move_para = new MovePara();
        show_envelop = false;
        show_joint = false;
        show_body = true;

        gameObject.AddComponent<Animation>();
        animation.AddClip(move_para.create_move(Movement.RUN), "run");
        animation.AddClip(move_para.create_move(Movement.JUMP), "jump");
        animation.AddClip(move_para.create_move(Movement.SLIDE), "slide");
	}
Esempio n. 4
0
        public void ReceiveTimesOut_Throws()
        {
            using (Socket localSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
            {
                using (Socket remoteSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
                {
                    localSocket.Bind(new IPEndPoint(IPAddress.IPv6Loopback, TestPortBase));
                    localSocket.Listen(1);
                    IAsyncResult localAsync = localSocket.BeginAccept(null, null);

                    remoteSocket.Connect(IPAddress.IPv6Loopback, TestPortBase);

                    Socket acceptedSocket = localSocket.EndAccept(localAsync);
                    acceptedSocket.ReceiveTimeout = 100;

                    SocketException sockEx = Assert.Throws<SocketException>( () =>
                    {
                        acceptedSocket.Receive(new byte[1]);
                    });
                    
                    Assert.Equal(SocketError.TimedOut, sockEx.SocketErrorCode);
                    Assert.True(acceptedSocket.Connected);
                }
            }
        }
Esempio n. 5
0
File: test.cs Progetto: mono/gert
	static void Main (string [] args)
	{
		int port;

		Random random = new Random ();
		Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

		do {
			port = random.Next (0xc350, 0xffdc);
			IPEndPoint localEP = new IPEndPoint (IPAddress.Loopback, port);
			try {
				socket.Bind (localEP);
				break;
			} catch {
			}
		} while (true);

		socket.Close ();

		IPEndPoint LocalEP = new IPEndPoint (IPAddress.Loopback, port);
		Socket ListeningSocket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
		ListeningSocket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
		ListeningSocket.Bind (LocalEP);
		ListeningSocket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
			new MulticastOption (IPAddress.Parse ("239.255.255.250"), IPAddress.Loopback));
		ListeningSocket.Close ();
	}
Esempio n. 6
0
    public static void StartListening()
    {
        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
        IPAddress ipAddress = ipHostInfo.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

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

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

            while (true)
            {
                AllDone.Reset();
                listener.BeginAccept(AcceptCallback, listener);
                AllDone.WaitOne();
            }
        }
        catch (Exception e)
        {
            throw;
        }
    }
Esempio n. 7
0
    public static void Sync_init()
    {
        sync_srv_state = true;
        Syncsck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        Syncsck.Bind(new IPEndPoint(IPAddress.Parse(RmIp), SyncPort));
        Syncsck.Listen(5);
        Syncsck.ReceiveTimeout = 12000;
        while (true)
        {
            try
            {
                Cmdsck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                Cmdsck.Connect(new IPEndPoint(IPAddress.Parse(RmIp), CmdPort));
                sync_srv_state = true;
            }
            catch
            {
                sync_srv_state = false;
                Console.WriteLine("Con. False");
                Thread.Sleep(5000);
            }
            if (sync_srv_state == true)
            {
                Thread Syncproc = new Thread(Sync_srv);
                Syncproc.Start();
                Thread.Sleep(5000);
                while (sync_srv_state == true) { Thread.Sleep(1000); }
                Cmdsck.Close();
            }
        }

    }
Esempio n. 8
0
        static void Main(string[] args)
        {
            using (var context = NetMQContext.Create())
            using (var udpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            using (var poller = new Poller())
            {
                // Ask OS to let us do broadcasts from socket
                udpSocket.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.Broadcast, 1);

                // Bind UDP socket to local port so we can receive pings
                udpSocket.Bind(new IPEndPoint(IPAddress.Any, PingPortNumber));

                // We use zmq_poll to wait for activity on the UDP socket, because
                // this function works on non-0MQ file handles. We send a beacon
                // once a second, and we collect and report beacons that come in
                // from other nodes:

                poller.AddPollInSocket(udpSocket, socket => { });
                poller.PollTillCancelledNonBlocking();
                //poller.ad
                //var poller = new z
                //var pollItemsList = new List<ZPollItem>();
                //pollItemsList.Add(new ZPollItem(ZPoll.In));
                //var pollItem = ZPollItem.CreateReceiver();
                //ZMessage message;
                //ZError error;
                //pollItem.ReceiveMessage(udpSocket, out message, out error);
                //pollItem.ReceiveMessage = (ZSocket socket, out ZMessage message, out ZError error) =>

                // Send first ping right away

            }
        }
Esempio n. 9
0
File: server.cs Progetto: mono/gert
	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);
	}
Esempio n. 10
0
 public void StartListening(int port) 
 { 
     try { // Resolve local name to get IP address 
         IPHostEntry entry = Dns.Resolve(Dns.GetHostName()); 
         IPAddress ip = entry.AddressList[0]; 
         // Create an end-point for local IP and port 
         IPEndPoint ep = new IPEndPoint(ip, port); 
         if(isLogging)
             TraceLog.myWriter.WriteLine ("Address: " + ep.Address.ToString() +" : " + ep.Port.ToString(),"StartListening"); 
         EventLog.WriteEntry("MMFCache Async Listener","Listener started on IP: " + 
                 ip.ToString() + " and Port: " +port.ToString()+ "."); 
         // Create our socket for listening 
         s = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp); 
         // Bind and listen with a queue of 100 
         s.Bind(ep); 
         s.Listen(100); 
         // Setup our delegates for performing callbacks 
         acceptCallback = new AsyncCallback(AcceptCallback); 
         receiveCallback = new AsyncCallback(ReceiveCallback); 
         sendCallback = new AsyncCallback(SendCallback); 
         // Set the "Accept" process in motion 
         s.BeginAccept(acceptCallback, s); 
     } 
     catch(SocketException e) { 
         Console.Write("SocketException: "+ e.Message); 
     } 
 } 
Esempio n. 11
0
        public void Initialize(IDatabaseHandler dbHandler)
        {
            GlobalContext = new Context(1);
            ValkWFStepPoller.PollContext = GlobalContext;
            ValkWFActivator.ActContext = GlobalContext;
            ValkQueueWFSteps.QueueContext = GlobalContext;
            //setup our inprocess communication
            ActivatorControlIntraComm = GlobalContext.Socket(SocketType.REQ);
            ActivatorControlIntraComm.Bind("inproc://activatorcontrol");
            //poller requires activator, goes after
            PollerControlIntraComm = GlobalContext.Socket(SocketType.REQ);
            PollerControlIntraComm.Bind("inproc://pollercontrol");

            QueueControlIntraComm = GlobalContext.Socket(SocketType.REQ);
            QueueControlIntraComm.Bind("inproc://queuecontrol");

            //anonymous function to pass in dbhandler without parameterizedthreadstart obscurities
            WFStepQueue = new Thread(() => ValkQueueWFSteps.RunQueue(dbHandler));
            WFStepQueue.Start();

            Activator = new Thread(() => ValkWFActivator.ActivateResponder(dbHandler));
            Activator.Start();

            Poller = new Thread(() => ValkWFStepPoller.StartPolling(dbHandler));
            Poller.Start();
        }
Esempio n. 12
0
    public ServerSocket()
    {
        data = new byte[102400];

        //得到本机IP,设置TCP端口号
        ipep = new IPEndPoint(IPAddress.Any, 6000);
        newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

        //绑定网络地址
        newsock.Bind(ipep);

        //得到客户机IP
        sender = new IPEndPoint(IPAddress.Any, 0);
        Remote = (EndPoint)(sender);

        ////客户机连接成功后,发送欢迎信息
        //string welcome = "Welcome ! ";

        ////字符串与字节数组相互转换
        //data = Encoding.ASCII.GetBytes(welcome);

        ////发送信息
        //newsock.SendTo(data, data.Length, SocketFlags.None, Remote);

        texture = new Texture2D(960, 720);

        thread = new Thread(start);
        thread.IsBackground = true;
        thread.Start();
        Debug.Log("Thread start");
    }
Esempio n. 13
0
    /// <summary>
    /// Socket Initialization Place Any Other Code Before the Socket Initialization
    /// </summary>
    private void Start()
    {
        limits.x = -4;
        limits.y =  8;
        limits.z =  4;

        AudioManager.Instance.PlaySound(EAudioPlayType.BGM, audioClip);

        if (toPototatoeFountainOrNotToPotatoeFountain)
        { StartCoroutine(POTATOFOUNTAIN()); } 

        if (socketBehaviour == ESocketBehaviour.Server)
        {
            clients = new List<Socket>();

            buffer = new byte[1024];

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

            IPEndPoint parsedIP = new IPEndPoint(IPAddress.Parse(IP), port);

            mySocket.Bind(parsedIP);
            mySocket.Listen(100);
            mySocket.BeginAccept( new AsyncCallback(AcceptCallback), null );

            return;
        }

        if (socketBehaviour == ESocketBehaviour.Client)
        {
            buffer = new byte[1];
        }
    }
Esempio n. 14
0
	 public void Start ()
	{
		if(clientSocket!=null && clientSocket.Connected)return ;

		//服务器端口
		IPEndPoint ipEndpoint = new IPEndPoint (IPAddress.Any,point);
		//创建Socket对象
		clientSocket = new Socket (AddressFamily.InterNetwork,socketType,protocolType);

		//这是一个异步的建立连接,当连接建立成功时调用connectCallback方法
		//IAsyncResult result = clientSocket.BeginConnect (ipEndpoint,new AsyncCallback (connectCallback),clientSocket);
		
		//这里做一个超时的监测,当连接超过5秒还没成功表示超时
		//bool success = result.AsyncWaitHandle.WaitOne( 5000, true );

		//绑定网络地址
		clientSocket.Bind(ipEndpoint);
		Debug.Log("This is a Server, host name is {"+Dns.GetHostName()+"}");

			//与socket建立连接成功,开启线程接受服务端数据。
			//worldpackage = new List<JFPackage.WorldPackage>();
			thread = new Thread(new ThreadStart(ReceiveSorket));
			thread.IsBackground = true;
			thread.Start();

	}
Esempio n. 15
0
	public UDPServer()
	{
		try
		{
			// Iniciando array de clientes conectados
			this.listaClientes = new ArrayList();
			entrantPackagesCounter = 0;
			sendingPackagesCounter = 0;			
			// Inicializando el delegado para actualizar estado
			//this.updateStatusDelegate = new UpdateStatusDelegate(this.UpdateStatus);
		
			// Inicializando el socket
			serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			
			// Inicializar IP y escuhar puerto 30000
			IPEndPoint server = new IPEndPoint(IPAddress.Any, 30001);
			
			// Asociar socket con el IP dado y el puerto
			serverSocket.Bind(server);
			
			// Inicializar IPEndpoint de los clientes
			IPEndPoint clients = new IPEndPoint(IPAddress.Any, 0);
			
			// Inicializar Endpoint de clientes
			EndPoint epSender = (EndPoint)clients;
			
			// Empezar a escuhar datos entrantes
			serverSocket.BeginReceiveFrom(this.dataStream, 0, this.dataStream.Length, SocketFlags.None, ref epSender, new AsyncCallback(ReceiveData), epSender);

		}
		catch (Exception ex)
		{
			//Debug.Log("Error al cargar servidor: " + ex.Message+ " ---UDP ");
		}
	}
        public void Success()
        {
            ManualResetEvent completed = new ManualResetEvent(false);

            if (Socket.OSSupportsIPv4)
            {
                using (Socket receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
                {
                    int port = receiver.BindToAnonymousPort(IPAddress.Loopback);
                    receiver.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);

                    Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    sender.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                    sender.SendTo(new byte[1024], new IPEndPoint(IPAddress.Loopback, port));

                    SocketAsyncEventArgs args = new SocketAsyncEventArgs();
                    args.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                    args.SetBuffer(new byte[1024], 0, 1024);
                    args.Completed += OnCompleted;
                    args.UserToken = completed;

                    Assert.True(receiver.ReceiveMessageFromAsync(args));

                    Assert.True(completed.WaitOne(Configuration.PassingTestTimeout), "Timeout while waiting for connection");

                    Assert.Equal(1024, args.BytesTransferred);
                    Assert.Equal(sender.LocalEndPoint, args.RemoteEndPoint);
                    Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, args.ReceiveMessageFromPacketInfo.Address);

                    sender.Dispose();
                }
            }
        }
 public MessagePublisher(OnTheWireBusConfiguration configuration)
 {
     _configuration = configuration;
     _context = new Context(configuration.MaxThreads);
     _publisher = _context.Socket(SocketType.PUB);
     _publisher.Bind(configuration.FullyQualifiedAddress);
 }
Esempio n. 18
0
        public void Success()
        {
            if (Socket.OSSupportsIPv4)
            {
                using (Socket receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
                {
                    int port = receiver.BindToAnonymousPort(IPAddress.Loopback);
                    receiver.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true);

                    Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                    sender.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                    sender.SendTo(new byte[1024], new IPEndPoint(IPAddress.Loopback, port));

                    IPPacketInformation packetInformation;
                    SocketFlags flags = SocketFlags.None;
                    EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);

                    int len = receiver.ReceiveMessageFrom(new byte[1024], 0, 1024, ref flags, ref remoteEP, out packetInformation);

                    Assert.Equal(1024, len);
                    Assert.Equal(sender.LocalEndPoint, remoteEP);
                    Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, packetInformation.Address);

                    sender.Dispose();
                }
            }
        }
	public static void StartListening()
	{
		// Data buffer for incoming data.     
		// Establish the local endpoint for the socket.     
		// The DNS name of the computer     
		// running the listener is "host.contoso.com".     
		//IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
		//IPAddress ipAddress = ipHostInfo.AddressList[0];
		IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
		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(100);
			while (!stop)
			{
				// Set the event to nonsignaled state.     
				allDone.Reset();
				// Start an asynchronous socket to listen for connections.     
				LogMgr.Log("Waiting for a connection...");
				listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
				// Wait until a connection is made before continuing.     
				allDone.WaitOne();
			}
		}
		catch (Exception e)
		{
			LogMgr.LogError(e);
		}

	}
 // Use this for initialization
 void Start()
 {
     // Set up Server End Point for sending packets.
     IPHostEntry serverHostEntry = Dns.GetHostEntry(serverIp);
     IPAddress serverIpAddress = serverHostEntry.AddressList[0];
     serverEndPoint = new IPEndPoint(serverIpAddress, serverPort);
     Debug.Log("Server IPEndPoint: " + serverEndPoint.ToString());
     // Set up Client End Point for receiving packets.
     IPHostEntry clientHostEntry = Dns.GetHostEntry(Dns.GetHostName());
     IPAddress clientIpAddress = IPAddress.Any;
     foreach (IPAddress ip in clientHostEntry.AddressList) {
         if (ip.AddressFamily == AddressFamily.InterNetwork) {
             clientIpAddress = ip;
         }
     }
     clientEndPoint = new IPEndPoint(clientIpAddress, serverPort);
     Debug.Log("Client IPEndPoint: " + clientEndPoint.ToString());
     // Create socket for client and bind to Client End Point (Ip/Port).
     clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     try {
         clientSocket.Bind(clientEndPoint);
     }
     catch (Exception e) {
         Debug.Log("Winsock error: " + e.ToString());
     }
 }
		public TZmqServer (TProcessor processor, Context ctx, String endpoint, SocketType sockType)
		{
			new TSimpleServer (processor,null);
			_socket = ctx.Socket (sockType);
			_socket.Bind (endpoint);
			_processor = processor;
		}
Esempio n. 22
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); }
        }
    }
Esempio n. 23
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();
	}
Esempio n. 24
0
File: server.cs Progetto: mono/gert
	Server ()
	{
		_listener = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		_listener.Bind (new IPEndPoint (IPAddress.Loopback, 10000));
		_listener.Listen (10);
		_listener.BeginAccept (new AsyncCallback (OnAccept), _listener);
	}
Esempio n. 25
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();
    }
Esempio n. 26
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();

    }
Esempio n. 27
0
        public void Start()
        {
            _receiver = _context.Socket(SocketType.PULL);
            _controller = _context.Socket(SocketType.PUB);

            _receiver.Bind("inproc://sink");
            _controller.Bind("inproc://controller");
        }
Esempio n. 28
0
    // Use this for initialization
    public void initServer()
    {
        host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        host.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8889));
        host.Listen(100);

        //host.Close();
    }
Esempio n. 29
0
 public void BeginAccept(int port)
 {
     Ipep = new IPEndPoint(IPAddress.Any, port);
     ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     ServerSocket.Bind(Ipep);
     ServerSocket.Listen(1);
     ServerSocket.BeginAccept(OnAccept, ServerSocket);
 }
Esempio n. 30
0
    public void query(zzHostInfo pHostInfo)
    {
        Socket lSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        lSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 1000);
        lSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

        lSocket.Bind(new IPEndPoint(IPAddress.Any, pHostInfo.port));
        Query(stunServerAddress, stunServerPort, lSocket);
    }
Esempio n. 31
0
        public void Bind(int port, string hostName)
        {
            var ipAddress     = Dns.GetHostEntry(hostName).AddressList[0];
            var localEndPoint = new IPEndPoint(ipAddress, port);

            _wrappedSocket = new Socket(
                ipAddress.AddressFamily,
                SocketType.Stream,
                ProtocolType.Tcp
                );
            _wrappedSocket?.Bind(localEndPoint);
        }
Esempio n. 32
0
        public void StartListening(/*object name*/)
        {
            // Data buffer for incoming data.
            byte[] bytes = new Byte[1024];

            IPEndPoint _server = new IPEndPoint(IPAddress.Parse("0.0.0.0"), 102);

            // Create a TCP/IP 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(_server);
                listener.Listen(100);

                while (true)
                {
                    // Set the event to nonsignaled state.
                    allDone.Reset();

                    // Start an asynchronous socket to listen for connections.
                    listener.BeginAccept(
                        new AsyncCallback(AcceptCallback),
                        listener);

                    // Wait until a connection is made before continuing.
                    allDone.WaitOne();
                }
            }
            catch (Exception e)
            {
                //MessageBox.Show(e.ToString());
            }
        }
        /// <summary>
        /// 开启服务器
        /// </summary>
        public void StartServer()
        {
            serverSocket.Bind(endPoint);
            serverSocket.Listen(listenNum);
            System.Console.WriteLine("服务器启动,等待客户端的连接...........");
            Socket clientSocket = serverSocket.Accept();

            DateTime startTime = DateTime.Now;

            byte[]     buffer         = new byte[1024];
            int        dataLength     = clientSocket.Receive(buffer);
            string     data           = Encoding.ASCII.GetString(buffer, 0, dataLength);
            IPEndPoint remoteEndPoint = (IPEndPoint)clientSocket.RemoteEndPoint;

            System.Console.WriteLine(remoteEndPoint.Address + ":" + remoteEndPoint.Port + " say :" + data);

            string sendData = @"I Have Got It!";

            byte[] sendbuffer = new byte[1024];
            sendbuffer = Encoding.ASCII.GetBytes(sendData);
            clientSocket.Send(sendbuffer);

            dataLength = clientSocket.Receive(buffer);
            data       = Encoding.ASCII.GetString(buffer, 0, dataLength);
            System.Console.WriteLine(remoteEndPoint.Address + ":" + remoteEndPoint.Port + " say :" + data);

            System.Console.WriteLine("通信结束..........");

            DateTime endTime = DateTime.Now;

            TimeSpan span = endTime - startTime;

            System.Console.WriteLine("使用时间(微秒):" + span.TotalMilliseconds);

            clientSocket.Dispose();
        }
Esempio n. 34
0
        public void Start()
        {
            this.Log().Info("Starting game server on port {0}", m_configuration.ListenPort);

            m_gameSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            m_gameSocket.Bind(new IPEndPoint(IPAddress.Any, m_configuration.ListenPort));

            m_gameSocket.Blocking = false;

            try
            {
                m_gameSocket6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
                m_gameSocket6.Bind(new IPEndPoint(IPAddress.IPv6Any, m_configuration.ListenPort));

                m_gameSocket6.Blocking = false;
            }
            catch (Exception ex)
            {
                this.Log().Error(() => "Couldn't create IPv6 socket. Exception message: " + ex.Message, ex);

                m_gameSocket6 = null;
            }

            m_receiveBuffer  = new byte[2048];
            m_receiveBuffer6 = new byte[2048];

            if (UseAsync)
            {
                m_asyncEventArgs = CreateAsyncEventArgs(m_gameSocket, m_receiveBuffer);

                if (m_gameSocket6 != null)
                {
                    m_asyncEventArgs6 = CreateAsyncEventArgs(m_gameSocket6, m_receiveBuffer6);
                }
            }
        }
Esempio n. 35
0
        public int StartListening()
        {
            //buffer incoming data
            byte[] buffer = new byte[1024];

            IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Parse(_ip), _port);

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

            try
            {
                //bind and listen
                _mainSocket.Bind(iPEndPoint);
                _mainSocket.Listen(100);

                Console.WriteLine("Socket Made");

                while (true)
                {
                    //set the event to non signaled
                    AllDone.Reset();

                    //start the async socket to listen for connection
                    Console.WriteLine("listening for connections");

                    _mainSocket.BeginAccept(new AsyncCallback(AcceptCallBack), _mainSocket);

                    //wait until accept is handled
                    AllDone.WaitOne();
                }
            }
            catch (Exception ex)
            {
                return(-1);
            }
        }
Esempio n. 36
0
        public void init()
        {
#if LuaDebugger
            try
            {
                IPEndPoint localEP = new IPEndPoint(IPAddress.Parse("0.0.0.0"), DebugPort);
                server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
                server.Bind(localEP);
                server.Listen(10);
                server.BeginAccept(new AsyncCallback(onClientConnect), server);
                Debug.Log("Opened lua debugger interface at " + localEP.ToString());

                // redirect output to client socket
                var luaFunc = state.getFunction("Slua.ldb.setOutput");
                luaFunc.call((LuaCSFunction)output);
            }
            catch (Exception e)
            {
                Debug.LogError(string.Format("LuaDebugger listened failed for reason::{0}", e.Message));
            }
#endif
        }
Esempio n. 37
0
 public void ThreadForAuth(IPEndPoint localEndPoint)
 {
     try
     {
         authSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         authSocket.Bind(localEndPoint);
         TextWrite("Ожидание подключений");
         button1.Enabled      = false;
         richTextBox2.Enabled = false;
         authSocket.Listen(10);
         while (true)
         {
             Socket handler = authSocket.Accept();
             Thread t       = new Thread(() => ThreadReceive(handler));
             userList.Add(handler, new UserInfo(t));
             t.IsBackground = true;
             t.Start();
         }
     }
     catch (Exception ex)
     {
         TextWrite(ex.ToString());
     }
 }
Esempio n. 38
0
        public void Start(string host, int post)
        {
            conns = new Conn[maxConn];
            for (int i = 0; i < maxConn; i++)
            {
                conns[i] = new Conn();
            }
            //Socket部分
            listenfd = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //Bind部分
            IPAddress  ipAdr = IPAddress.Parse(host);
            IPEndPoint ipEp  = new IPEndPoint(ipAdr, post);

            listenfd.Bind(ipEp);
            //Listen部分
            listenfd.Listen(maxConn);             //最多可容纳的接收数
            //Accept部分
            listenfd.BeginAccept(AcceptCb, null); //非阻塞

            Console.WriteLine("[服务器]正在等待连接..");
            timer.Elapsed  += new System.Timers.ElapsedEventHandler(HandleMainTimer);
            timer.AutoReset = false; //只执行一次
            timer.Enabled   = true;
        }
Esempio n. 39
0
        private static void StartClient()
        {
            // Connect to a remote device.
            try
            {
                Debug.Log("[UDP] Starting client");
                _dataStream = new DataStream();
                client      = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                //client.ExclusiveAddressUse = false;

                IPEndPoint ipep = new IPEndPoint(IPAddress.Any, _dataPort);
                client.Bind(ipep);

                IPAddress ip = IPAddress.Parse(_multicastIPAddress);
                client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, IPAddress.Any));

                _isInitRecieveStatus = Receive(client);
                _isIsActiveThread    = _isInitRecieveStatus;
            } catch (Exception e)
            {
                Debug.LogError("[UDP] DirectMulticastSocketClient: " + e.ToString());
            }
        }
Esempio n. 40
0
        static void Main(string[] args)
        {
            Socket sock = new Socket(AddressFamily.InterNetwork,
                                     SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);

            sock.Bind(iep);
            EndPoint ep = (EndPoint)iep;

            Console.WriteLine("Ready To Receiv...!");
            byte[] data = new byte[1024];
            while (sock.Poll(10000000, SelectMode.SelectRead))
            {
                int recv = sock.ReceiveFrom(data, ref ep);
                sock.SendTo(data, iep);
                string stringData = Encoding.ASCII.GetString(data, 0, recv);
                Console.WriteLine("Received: {0} from: {1}", stringData, ep.ToString());
                data       = new byte[1024];
                recv       = sock.ReceiveFrom(data, ref ep);
                stringData = Encoding.ASCII.GetString(data, 0, recv);
                Console.WriteLine("Received: {0} from: {1}", stringData, ep.ToString());
            }
            sock.Close();
        }
Esempio n. 41
0
        //Listen for ClientConnection on port
        public void Listen(ushort port)
        {
            local_security = new Security();
            local_security.GenerateSecurity(true, true, true);

            local_recv_buffer = new TransferBuffer(MAX_RECV_SIZE, 0, 0);
            local_listener    = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            local_socket      = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                if (local_listener.IsBound == false)
                {
                    local_listener.Bind(new IPEndPoint(IPAddress.Loopback, port));
                    local_listener.Listen(1);
                }
                local_listener.BeginAccept(new AsyncCallback(OnClientConnect), null);
                Console.WriteLine("Listing for Client on 127.0.0.1:" + port);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    public static void StartListening()
    {
        try{
            if (!intialized)
            {
                intialized = true;

                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();
            }

            do
            {
                data  = null;
                bytes = new byte[1024];
                int bytesRec = handler.Receive(bytes);
                data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
            }while (data == "\n");
            // Show the data on the console.
            Console.WriteLine("Text received : {0}", data);

            //handler.Shutdown(SocketShutdown.Both);
            //  handler.Close();
            //}
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
Esempio n. 43
0
        protected override void Start(CancellationToken token)
        {
            base.Start(token);

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

            token.Register(() => {
                listener.Close();
                connectArgs.Dispose();
            });

            listener.Bind(OriginalEndPoint);
            LocalEndPoint = (IPEndPoint)listener.LocalEndPoint;

            listener.Listen(6);

            connectArgs.Completed += OnSocketReceived;

            if (!listener.AcceptAsync(connectArgs))
            {
                OnSocketReceived(listener, connectArgs);
            }
        }
Esempio n. 44
0
        public Server()
        {
            // 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");
            //IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 65433);

            // Create a TCP/IP 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);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                Environment.Exit(1);
            }
        }
Esempio n. 45
0
        private ArrayList m_aryClients = new ArrayList();       // List of Client Connections

        public void start()
        {
            // Determine the IPAddress of this machine
            String strHostName = "";

            IPAddress[] aryLocalAddr = null;

            try
            {
                // NOTE: DNS lookups are nice and all but quite time consuming.
                strHostName = Dns.GetHostName();
                IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
                aryLocalAddr = ipEntry.AddressList;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error trying to get local address {0} ", ex.Message);
            }

            // Verify we got an IP address. Tell the user if we did
            if (aryLocalAddr == null || aryLocalAddr.Length < 1)
            {
                Console.WriteLine("Unable to get local address");
                return;
            }
            Console.WriteLine("Listening on : [{0}] {1}:{2}", strHostName, aryLocalAddr[0], nPortListen);

            // Create the listener socket in this machines IP address
            listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listener.Bind(new IPEndPoint(aryLocalAddr[0], nPortListen));
            //listener.Bind( new IPEndPoint( IPAddress.Loopback, nPortListen ) );	// For use with localhost 127.0.0.1
            listener.Listen(10);

            // Setup a callback to be notified of connection requests
            listener.BeginAccept(new AsyncCallback(OnConnectRequest), listener);
        }
Esempio n. 46
0
 //-----------------------------------------------------------
 // Control functions (Start, Stop, etc...)
 //-----------------------------------------------------------
 public void Start(int port)
 {
     _log4 = log4net.LogManager.GetLogger("MCEControl");
     try {
         _log4.Debug("SocketServer Start");
         // Create the listening socket...
         _mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         var ipLocal = new IPEndPoint(IPAddress.Any, port);
         // Bind to local IP Address...
         _log4.Debug("Binding to IP address: " + ipLocal.Address + ":" + ipLocal.Port);
         _mainSocket.Bind(ipLocal);
         // Start listening...
         _log4.Debug("_mainSocket.Listen");
         _mainSocket.Listen(4);
         // Create the call back for any client connections...
         SetStatus(ServiceStatus.Started);
         SetStatus(ServiceStatus.Waiting);
         _mainSocket.BeginAccept(OnClientConnect, null);
     }
     catch (SocketException se) {
         SendNotification(ServiceNotification.Error, CurrentStatus, null, String.Format("Start: {0}, {1:X} ({2})", se.Message, se.HResult, se.SocketErrorCode));
         SetStatus(ServiceStatus.Stopped);
     }
 }
        static void Main()
        {
            if (PortInUse(8888))
            {
                MessageBox.Show("AppServer已经打开或者8888端口被占用");
            }
            else
            {
                ConsoleWin32Helper.ShowNotifyIcon();  //显示系统托盘

                IPAddress ip = IPAddress.Parse("0.0.0.0");
                serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                serverSocket.Bind(new IPEndPoint(ip, myPort));
                serverSocket.Listen(10);
                Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
                Thread myThread = new Thread(ListenClientConnect);
                myThread.Start();

                while (true)
                {
                    Application.DoEvents(); //用Application.DoEvents()来捕获消息事件处理,但是要用死循环来控制
                }
            }
        }
Esempio n. 48
0
        /// <summary>
        /// 开始监听
        /// </summary>
        /// <param name="localIp"></param>
        /// <param name="localPort"></param>
        public static void BeginListening(string localIp, string localPort, ListBox listbox, ListBox listboxOnline)
        {
            //基本参数初始化
            lstbxMsgView = listbox;
            listbOnline  = listboxOnline;

            //创建服务端负责监听的套接字,参数(使用IPV4协议,使用流式连接,使用Tcp协议传输数据)
            socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //获取Ip地址对象
            IPAddress address = IPAddress.Parse(localIp);
            //创建包含Ip和port的网络节点对象
            IPEndPoint endpoint = new IPEndPoint(address, int.Parse(localPort));

            //将负责监听的套接字绑定到唯一的Ip和端口上
            socketWatch.Bind(endpoint);
            //设置监听队列的长度
            socketWatch.Listen(10);
            //创建负责监听的线程,并传入监听方法
            threadWatch = new Thread(WatchConnecting);
            threadWatch.IsBackground = true; //设置为后台线程
            threadWatch.Start();             //开始线程
            //ShowMgs("服务器启动监听成功");
            ShwMsgForView.ShwMsgforView(lstbxMsgView, "服务器启动监听成功");
        }
        private void SetupServerSocket(int inputPort)
        {
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), inputPort);

            // Create the socket, bind it, and start listening
            serverSocket = new Socket(AddressFamily.InterNetwork,
                                      SocketType.Stream, ProtocolType.Tcp);
            serverSocket.Blocking = false;

            try
            {
                serverSocket.Bind(localEndPoint);
                serverSocket.Listen(10);
            }
            catch (SocketException exc)
            {
                Console.WriteLine(ERROR_SYMBOL + "Socket exception: " + exc.SocketErrorCode);
                Console.WriteLine(exc);
            }
            catch (Exception exc)
            {
                Console.WriteLine(ERROR_SYMBOL + "Exception: " + exc);
            }
        }
Esempio n. 50
0
        // in taabe baraye injade connection beyne 2 computer neveshte shode ast. 2 EndPoint misaze ke har kodoome ye ip
        //darand va ye port. yeki baraye computere maghsad, yeki ham barayae computere manba
        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                epLocal = new IPEndPoint(IPAddress.Parse(GetLocalIP()), Convert.ToInt32(txtClient1Port.Text));
                sk.Bind(epLocal);
                SocketAsyncEventArgs s = new SocketAsyncEventArgs();

                Listen(Convert.ToInt32(txtClient2Port.Text));
                epRemote = new IPEndPoint(IPAddress.Parse(GetLocalIP()), Convert.ToInt32(txtClient2Port.Text));
                sk.Connect(epRemote);
                byte[] buffer = new byte[1500];
                sk.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);

                btnStart.Text    = "متصل";
                btnStart.Enabled = false;
                btnsend.Enabled  = true;
                txtmessage.Focus();
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.ToString());
            }
        }
Esempio n. 51
0
        static void Main()
        {
            int recv;

            byte[]     data    = new byte[4];
            IPEndPoint ipep    = new IPEndPoint(IPAddress.Any, 9050);
            Socket     newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            newsock.Bind(ipep);
            Console.WriteLine("Waiting for a client...");
            IPEndPoint ipClient = new IPEndPoint(IPAddress.Any, 0);
            EndPoint   Remote   = (EndPoint)(ipClient);

            recv = newsock.ReceiveFrom(data, ref Remote);
            int    clientChoosen = BitConverter.ToInt32(data, 0);
            Random rand          = new Random();
            int    serverChoosen = rand.Next(0, 2);

            if (clientChoosen == serverChoosen)
            {
                byte[] resul = Encoding.ASCII.GetBytes("Hoa");
                newsock.SendTo(resul, Remote);
            }
        }
Esempio n. 52
0
        static void Main(string[] args)
        {
            Socket     server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ipep   = new IPEndPoint(IPAddress.Any, 1234);

            server.Bind(ipep);
            byte[]   nhan = new byte[1024];
            EndPoint ep   = ipep;

            server.ReceiveFrom(nhan, ref ep);
            string s = Encoding.ASCII.GetString(nhan);

            Console.WriteLine("{0}", s);

            string r = "Hello Client!";
            string e = Encrypt(r, "mykey");
            string d = Decrypt(e, "mykey");
            string a = e + " Co nghia la " + d;

            byte[] gui = Encoding.ASCII.GetBytes(a);
            server.SendTo(gui, ep);

            server.Close();
        }
Esempio n. 53
0
        private Socket Bind(IPEndPoint ipep)
        {
            Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                s.Bind(ipep);
                s.Listen(300);

                s.BeginAccept(m_OnAccept, s);

                return(s);
            }
            catch
            {
                try { s.Shutdown(SocketShutdown.Both); }
                catch {}

                try { s.Close(); }
                catch {}

                return(null);
            }
        }
Esempio n. 54
0
        static void Main(string[] args)
        {
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sck.Bind(new IPEndPoint(0, 1234));
            sck.Listen(100);

            Socket accepted = sck.Accept();

            Buffer = new byte[accepted.SendBufferSize];
            int bytesRead = accepted.Receive(Buffer);

            byte[] formatted = new byte[bytesRead];

            for (int i = 0; i < bytesRead; i++)
            {
                formatted[i] = Buffer[i];
            }
            string strData = Encoding.ASCII.GetString(formatted);

            Console.Write(strData + "\n");
            Console.Read();
            sck.Close();
            accepted.Close();
        }
Esempio n. 55
0
        //Server thread function.
        private void ServerListening()
        {
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            serverIep    = new IPEndPoint(IPAddress.Any, Port);

            serverSocket.Bind(serverIep);
            serverSocket.Listen(ClientNumber);

            OutputTextbox.BeginInvoke(txtDelegate,
                                      "-- " + Properties.strings.chatroomTitle
                                      + " " + Properties.strings.listeningAtPort + " " + Port,
                                      OutputTextbox, true);

            while (ServerWorking)
            {
                ClientHandler client = new ClientHandler(serverSocket.Accept(), this);
                lock (serverLocker)
                    if (ServerWorking)
                    {
                        connectedClients.Add(client);
                    }
                RefreshInfo();
            }
        }
Esempio n. 56
0
        static void Main(string[] args)
        {
            IPHostEntry host          = Dns.GetHostEntry("localhost");
            IPAddress   ipAddress     = host.AddressList[0];
            IPEndPoint  localEndPoint = new IPEndPoint(ipAddress, 49321);

            // Create a Socket that will use Tcp protocol
            Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            // A Socket must be associated with an endpoint using the Bind method
            listener.Bind(localEndPoint);
            // Specify how many requests a Socket can listen before it gives Server busy response.
            // We will listen 10 requests at a time
            listener.Listen(10);

            Console.WriteLine("Waiting for a connection...");
            Socket handler = listener.Accept();

            string data = null;

            byte[] bytes = null;

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

            Console.WriteLine("Text received : {0}", data);

            byte[] msg = Encoding.ASCII.GetBytes(data);

            Console.Read();
        }
        public Task ExecutionContext_FlowsOnlyOnceAcrossAsyncOperations()
        {
            return Task.Run(async () => // escape xunit's sync ctx
            {
                using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
                {
                    listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
                    listener.Listen(1);

                    client.Connect(listener.LocalEndPoint);
                    using (Socket server = listener.Accept())
                    {
                        int executionContextChanges = 0;
                        var asyncLocal = new AsyncLocal<int>(_ => executionContextChanges++);
                        Assert.Equal(0, executionContextChanges);

                        int numAwaits = 20;
                        for (int i = 1; i <= numAwaits; i++)
                        {
                            asyncLocal.Value = i;

                            await new AwaitWithOnCompletedInvocation<int>(
                                client.ReceiveAsync(new Memory<byte>(new byte[1]), SocketFlags.None),
                                () => server.Send(new byte[1]));

                            Assert.Equal(i, asyncLocal.Value);
                        }

                        // This doesn't count EC changes where EC.Run is passed the same context
                        // as is current, but it's the best we can track via public API.
                        Assert.InRange(executionContextChanges, 1, numAwaits * 3); // at most: 1 / AsyncLocal change + 1 / suspend + 1 / resume
                    }
                }
            });
        }
Esempio n. 58
0
        //=================================================================================
        #region 构造和析构

        public KCPSocket(int bindPort, uint kcpKey, AddressFamily family = AddressFamily.InterNetwork)
        {
            m_AddrFamily = family;
            m_KcpKey     = kcpKey;
            m_ListKcp    = new List <KCPProxy>();

            m_SystemSocket = new Socket(m_AddrFamily, SocketType.Dgram, ProtocolType.Udp);
            IPEndPoint ipep = GetIPEndPointAny(m_AddrFamily, bindPort);

            m_SystemSocket.Bind(ipep);

            bindPort = (m_SystemSocket.LocalEndPoint as IPEndPoint).Port;
            LOG_TAG  = "KCPSocket[" + bindPort + "-" + kcpKey + "]";

            m_IsRunning  = true;
            m_ThreadRecv = new Thread(Thread_Recv)
            {
                IsBackground = true
            };
            m_ThreadRecv.Start();



#if UNITY_EDITOR_WIN
            uint IOC_IN            = 0x80000000;
            uint IOC_VENDOR        = 0x18000000;
            uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
            m_SystemSocket.IOControl((int)SIO_UDP_CONNRESET, new byte[] { Convert.ToByte(false) }, null);
#endif


#if UNITY_EDITOR
            UnityEditor.EditorApplication.playmodeStateChanged -= OnEditorPlayModeChanged;
            UnityEditor.EditorApplication.playmodeStateChanged += OnEditorPlayModeChanged;
#endif
        }
Esempio n. 59
0
        public void RequestConnection(int portNo)
        {
            serverPort = portNo;

            // Socket 인스턴스 초기화
            mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // 서버의 주소, 포트 번호 지정
            // 생성한 serverEp의 주소, 포트 번호를 이용해 소켓에 연결
            // 접속 허용자 수 20
            IPEndPoint serverEp = new IPEndPoint(IPAddress.Any, portNo);

            mainSocket.Bind(serverEp);
            mainSocket.Listen(20);

            AppendText("Server started");

            SocketAsyncEventArgs AsyncEvent = new SocketAsyncEventArgs();

            // 클라이언트가 접속했을 때 이벤트
            // 클라이언트 접속 대기
            AsyncEvent.Completed += new EventHandler <SocketAsyncEventArgs>(AcceptCompleted);
            mainSocket.AcceptAsync(AsyncEvent);
        }
Esempio n. 60
0
        public ServerCore(string host, int portControl, int maxLengthQueue, int sendFrequency)
        {
            this.portControl    = portControl;
            this.maxLengthQueue = maxLengthQueue;
            this.ipAdress       = IPAddress.Parse(host);
            this.bufferSize     = 1024 * 1024;
            this.idCounter      = 0;


            this.ipEndPointControl = new IPEndPoint(ipAdress, portControl);

            this.socketListener = new Socket(ipAdress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            this.socketsList = new List <Socket>();
            this.serializer  = new BinaryFormatter();
            try
            {
                socketListener.Bind(ipEndPointControl);
            }
            catch (Exception e)
            {
                throw e;
            }
        }