AcceptSocket() 공개 메소드

public AcceptSocket ( ) : Socket
리턴 Socket
        //Clienter der kan tilkoble serveren
        private void Run()
        {
            string productInformation = Console.ReadLine();

            try
            {
                string[] splitProduct = productInformation.Split('|');
                _product = new Product(splitProduct[0], double.Parse(splitProduct[1]), splitProduct[2]);
                Console.WriteLine("[" + GetDatetime() + "] Server: Produktet er blevet oprettet");
            }
            catch (Exception)
            {
                Console.WriteLine("[" + GetDatetime() + "] Server: Du har indtastet produktet i et ugyldigt format! Prøv igen.");
                Run();
            }

            TcpListener _tcpListener = new TcpListener(IPAddress.Any, _port);
            _tcpListener.Start();

            while (true)
            {
                Socket socket = _tcpListener.AcceptSocket();
                _clientIP = socket.RemoteEndPoint as IPEndPoint;

                Console.WriteLine("[" + GetDatetime() + "] Server: {0} er forbundet til serveren.", _clientIP.Address);
                ClientHandler clientHandler = new ClientHandler(socket, _product, _service, _clientIP);
                Thread clientThread = new Thread(clientHandler.Run);
                clientThread.Start();
            }
        }
예제 #2
1
 //Connect to the client
 public void connect()
 {
     if (!clientConnected)
     {
         IPAddress ipAddress = IPAddress.Any;
         TcpListener listener = new TcpListener(ipAddress, portSend);
         listener.Start();
         Console.WriteLine("Server is running");
         Console.WriteLine("Listening on port " + portSend);
         Console.WriteLine("Waiting for connections...");
         while (!clientConnected)
         {
             s = listener.AcceptSocket();
             s.SendBufferSize = 256000;
             Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);
             byte[] b = new byte[65535];
             int k = s.Receive(b);
             ASCIIEncoding enc = new ASCIIEncoding();
             Console.WriteLine("Received:" + enc.GetString(b, 0, k) + "..");
             //Ensure the client is who we want
             if (enc.GetString(b, 0, k) == "hello" || enc.GetString(b, 0, k) == "hellorcomplete")
             {
                 clientConnected = true;
                 Console.WriteLine(enc.GetString(b, 0, k));
             }
         }
     }
 }
예제 #3
1
        public void StartListening()
        {
            R = RowacCore.R;
            R.Log("[Listener] Starting TCP listener...");
            TcpListener listener = new TcpListener(IPAddress.Any, 28165);
            listener.Start();

            while (true)
            {
                try
                {
                    var client = listener.AcceptSocket();
            #if DEBUG
                    R.Log("[Listener] Connection accepted.");
            #endif

                    var childSocketThread = new Thread(() =>
                    {
                        byte[] data = new byte[1048576]; // for screenshots and tasklists
                        int size = 0;
                        while (client.Available != 0)
                            size += client.Receive(data, size, 256, SocketFlags.None); // TODO: increase reading rate from 256?
                        client.Close();

                        string request = Encoding.ASCII.GetString(data, 0, size);
            #if DEBUG
                        R.Log(string.Format("Received [{0}]: {1}", size, request));
            #endif
                        ParseRequest(request);
                    });
                    childSocketThread.Start();
                }
                catch (Exception ex) { R.LogEx("ListenerLoop", ex); }
            }
        }
예제 #4
0
 private void GetCloseIF()
 {
     try
     {
         TcpListener Lis = new TcpListener(7777);
         Lis.Start();
         Socket lissocket = Lis.AcceptSocket();
         while (true)
         {
             NetworkStream ns = new NetworkStream(lissocket);
             byte[] bb = new byte[1024];
             int len = ns.Read(bb, 0, bb.Length);
             String str = System.Text.Encoding.Default.GetString(bb, 0, len);
             //MessageBox.Show("Receive String " + str);
             if (str == "END")
             {
                 //MessageBox.Show("Got End Command!");
                 this.tm.Stop();
                 Lis.Stop();
                 this.Close();
                 break;
             }
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show("EEEEEEEEEEEE " + ex.ToString());
     }
 }
예제 #5
0
        public override void ShowUsage()
        {
            //NetWorkStream类是专门用来处理服务器与客户端通信的流。它在网络编程中经常使用,主要是用来处理类似Socket、TcpClient和TcpListener这些类中得到的流。
            //服务器端
            TcpListener lis = new TcpListener(5000);                        //服务器监听
            lis.Start();//启动
            Socket sock = lis.AcceptSocket();                               //阻塞,直到有客户端连接

            NetworkStream netStream = new NetworkStream(sock);              //得到Socket中的流
            if (netStream.DataAvailable)                                    //如果客户端发送了消息
            {
                byte[] data = new byte[1024];                               //定义一个字节数组,用来存放接收的数据
                int len = netStream.Read(data, 0, data.Length);             //从位置开始,读取到字节数组末尾
                string line = Encoding.Default.GetString(data, 0, len);     //把收到的字节转换为字符串
            }

            //客户端
            TcpClient client = new TcpClient();                             //客户端tcp对象
            client.Connect("127.0.0.1", 5000);                              //连接服务器
            NetworkStream myStream = client.GetStream();                    //得到网络流

            byte[] data2 = Encoding.Default.GetBytes("Hi,你好");           //首先把输入的字符串消息转换为字节
            myStream.Write(data2, 0, data2.Length);                         //向myStream 里写入数据
            myStream.Flush();                                               //刷新流中的数据
            myStream.Close();
        }
예제 #6
0
        /// <summary>
        /// Gets request from client, and sends back file/folder to encrypt
        /// </summary>
        static void handleRequest(TcpListener listener)
        {
            while (true)
            {
                int bytesRead;
                byte[] buffer = new byte[1024];
                string test = null;

                Socket s = listener.AcceptSocket();
                Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

                bytesRead = s.Receive(buffer);

                char cc = ' ';

                Console.WriteLine("Recieved...");
                for (int i = 0; i < bytesRead - 1; i++)
                {
                    //Console.Write(Convert.ToChar(buffer[i]));
                    cc = Convert.ToChar(buffer[i]);
                    test += cc.ToString();
                }

                Console.WriteLine(test);
                string message = "files encrypted.";

                ASCIIEncoding asen = new ASCIIEncoding();
                s.Send(asen.GetBytes(message));
                s.Close();
                Console.WriteLine("sent bytes back");
            }
        }
예제 #7
0
        private static void Main(string[] args)
        {
            var ip = IPAddress.Parse("127.0.0.1");
            var listener = new TcpListener(ip, 8080);

            while (true)
            {
                listener.Start();
                Console.WriteLine("Waiting for Connection...");

                using (var socket = listener.AcceptSocket())
                {
                    Console.WriteLine("Client Connected.");

                    var data = new byte[8];
                    socket.Receive(data);
                    var input = Encoding.Default.GetString(data).TrimEnd('\0');

                    Console.WriteLine("Client requested: {0}", input);

                    var response = Encoding.Default.GetBytes("OK");

                    socket.Send(response);

                    Console.WriteLine("Response sent to Client: {0}", "OK");
                    Console.WriteLine();
                }
            }
        }
예제 #8
0
        /// <summary>
        /// The main loop waiting for incoming connections
        /// </summary>
        public void ServerLoop()
        {
            try
            {

                listen = new TcpListener(IPAddress.Any, 8001);
                listen.Start();

                Console.WriteLine("Server running at port 8001");
                Console.WriteLine("The local endpoint is " + listen.LocalEndpoint);
                Console.WriteLine("Waiting for connection");

                Socket s;

                while (true)
                {
                    s = listen.AcceptSocket();
                    Console.WriteLine("Succesfully connected to " + s.RemoteEndPoint);
                    ConnectedClients.Add(s);
                    Task.Factory.StartNew(() => ClientConnectedLoop(s));
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.StackTrace);
            }
        }
예제 #9
0
        public void listenClient()
        {
            LocalAddress = IPAddress.Parse("127.0.0.1");
            tcpListener = new TcpListener(LocalAddress,PORT_RECEIVE);
            tcpListener.Start();

            while(true)
            {
                Socket socket = tcpListener.AcceptSocket();
                NetworkStream netStream = new NetworkStream(socket);
                StreamReader sReader = new StreamReader(netStream);
                fileName = sReader.ReadLine();
                if (list_Files.Contains(fileName)&&fileName=="Quit") break;
                list_Files.Add(fileName);
                string Path="E:/" + fileName;
                FileStream InputFile = new FileStream(Path, FileMode.CreateNew, FileAccess.Write, FileShare.None);
                BinaryWriter BinaryStream = new BinaryWriter(InputFile);
                byte[] data = new byte[BUFFER];
                do
                {
                    socket.Receive(data);
                    BinaryStream.Write(data);

                } while (data.Length != 0);
                BinaryStream.Flush();
                BinaryStream.Close();
                InputFile.Close();

            }
        }
예제 #10
0
        static void Main(string[] args)
        {
            LinkedList<Client> listeClient = new LinkedList<Client>();

            int port = 6666;

            //on se déclare une oreille TCP sur un port spécifique
            TcpListener serveur = new TcpListener(System.Net.IPAddress.Any,port);

            //on la démarre....
            serveur.Start();

            //tant que le serveur est en vie on tourne en rond
            while (true)
            {
                Console.WriteLine(">> On attend une connexion");
                // cette ligne bloque tant que l'oreille n'entends pas une connexion
                Socket socketClient = serveur.AcceptSocket();

                Client client = new Client(socketClient,listeClient);

                ThreadStart ts = new ThreadStart(client.Thread);
                Thread trd = new Thread(ts);
                trd.Start();
            }
        }
예제 #11
0
        public LoopbackTcpStream(params byte[] initialStagedReadBytes)
        {
            var tcpListener = new SystemTcpListener(IPAddress.Loopback, 0);

            try
            {
                tcpListener.Start();
                var clientSocket = new Socket(SocketType.Stream, ProtocolType.Tcp)
                {
                    NoDelay = true
                };
                clientSocket.Connect(tcpListener.LocalEndpoint);
                this._senderStream = new NetworkStream(clientSocket, true);
                var receiverSocket = tcpListener.AcceptSocket();
                this._receiverStream = new NetworkStream(receiverSocket, true);
                this.LocalEndPoint   = receiverSocket.LocalEndPoint;
                this.RemoteEndPoint  = receiverSocket.RemoteEndPoint;

                this._writtenBytes = new BufferBlock <byte>();
            }
            finally
            {
                tcpListener.Stop();
            }

            if (initialStagedReadBytes != null)
            {
                this.StageReadBytes(initialStagedReadBytes);
            }
        }
예제 #12
0
        public WebServer(int port, string root)
        {
            /* this script processor instance will be used to process files of type
             * csscript */
            _scriptProcessor = new CscriptProcessor();

            /*TODO: add another instance of a IScriptProcessor to handle files of
             * type csweb */
            _webTemplateProcessor = new CWebTemplateProcessor();

            /* set the root for the server */
            _webRoot = root;

            /* create a TcpListener to listen for netweork requests on the provided
             * port number at the lookedup host address and start listening */
            TcpListener listener = new TcpListener(
                Dns.GetHostAddresses("localhost")[0], port);
            listener.Start();
            Console.WriteLine("Web server listening on port {0}", port);

            /* main body of the web server, this will listen for requests,
             * open a socket with the client when a request is received
             * and spawn a process thread for accepting the request and
             * return to listen for the next request */
            while (true)
            {
                Socket soc = listener.AcceptSocket();
                new Task(delegate()
                {
                    AcceptRequest(soc);
                }).Start();
            }
        }
        static void Main(string[] args)
        {
            try
            {
                tcpListener = new TcpListener(IPAddress.Any, 100);
                tcpListener.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Could not start the server on Port 100:");
                Console.WriteLine(ex.Message);
                Console.ReadLine();
                Environment.Exit(-1);
            }

            try
            {
                while (true)
                {
                    new Thread(new Client(tcpListener.AcceptSocket()).Start).Start();
                    Console.WriteLine("New Player connected");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Could not listen on Port 100:");
                Console.WriteLine(ex.Message);
                Console.ReadLine();
                Environment.Exit(-1);
            }
        }
예제 #14
0
        public static void Main1(string[] args)
        {
            string name = "localhost";
            IPAddress[] addrs = Dns.GetHostEntry(name).AddressList;

            Console.WriteLine(addrs[0]);
            Console.WriteLine(addrs[1]);

            //TcpListener welcomeSocket = new TcpListener(addrs[1], 6789);
            //IPAddress ip = IPAddress.Parse("127.0.0.1");
            //TcpListener serverSocket = new TcpListener(ip, 6789);

            TcpListener serverSocket = new TcpListener(6789);
            serverSocket.Start();

            while (true)
            {
                Socket connectionSocket = serverSocket.AcceptSocket();
                Console.WriteLine("Server activated now");
                WebServerhelper service = new WebServerhelper(connectionSocket);
                service.DoIt();

            }

            serverSocket.Stop();
        }
예제 #15
0
 public static Messenger Make(int port) {
     var listener = new TcpListener(IPAddress.Any, port);
     listener.Start();
     Socket socket = listener.AcceptSocket();
     listener.Stop();
     return new Messenger(new SocketModelImpl(socket));
 }
예제 #16
0
        public void SendFile(string fileName)
        {
            tcpListener2 = new TcpListener(LocalAddress,PORT_SEND);
            tcpListener2.Start();

            while(true)
            {
                Socket socket  = tcpListener2.AcceptSocket();

                NetworkStream netStream = new NetworkStream(socket);
                StreamWriter sWriter = new StreamWriter(netStream);

                string Path="E:/" + fileName;
                FileInfo File = new FileInfo(Path);
                if (list_Files.Contains(fileName)&&fileName=="Quit") break;
                list_Files.Add(fileName);
                filePath= "E:/" + fileName;
                FileStream InputFile = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write, FileShare.None);
                BinaryWriter BinaryStream = new BinaryWriter(InputFile);
                byte[] data = new byte[BUFFER];
                do
                {
                    socket.Receive(data);
                    BinaryStream.Write(data);

                } while (data.Length != 0);
                BinaryStream.Flush();
                BinaryStream.Close();
                InputFile.Close();

            }
        }
예제 #17
0
        /// <summary>
        /// Start the listener for incoming messages
        /// </summary>
        public void Start()
        {
            tcpListener = new TcpListener(System.Net.IPAddress.Any, this.port);
            tcpListener.Start();
            Console.WriteLine("Server Started") ;
            this.IsListening = true;

            try
            {
                while (isListening)
                {
                    Console.WriteLine("Server listening...");
                    Socket socketForClient = tcpListener.AcceptSocket();
                    Console.WriteLine("Client connected");
                    NetworkStream networkStream = new NetworkStream(socketForClient);

                    BinaryFormatter bf = new BinaryFormatter();
                    Object message = (RemoteMessage)bf.Deserialize(networkStream);

                    networkStream.Flush();

                    interpretMessage((RemoteMessage)message);

                    socketForClient.Disconnect(true);
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(e.ToString()) ;
            }
        }
예제 #18
0
 private static void Listen(int index)
 {
     try
     {
         TcpListener listener = new TcpListener(Config.Addresses[index], Config.Ports[index]);
         listener.Start();
         IrcServer.Logger.Log(LogLevel.Info, "Listening on {0}:{1}", Config.Addresses[index], Config.Ports[index]);
         while (true)
         {
             Socket client = listener.AcceptSocket();
             new IrcClient
             {
                 Socket = client,
                 IrcServer = Server
             }.OnConnect();
         }
     }
     catch (Exception ex)
     {
         IrcServer.Logger.Log(LogLevel.Error,
             "The IRC Server at {0}:{1} encountered an error and is no longer listening.",
             Config.Addresses[index],
             Config.Ports[index]);
         IrcServer.Logger.Log(ex);
     }
 }
예제 #19
0
파일: ClientCore.cs 프로젝트: Ikthios/P2P
        public void StartClientServer(String ip, int port)
        {
            string ipString = ip.ToString();
            // Parse client ip address
            IPAddress ipaddress = IPAddress.Parse(ipString);  // Format exception

            // Initialize client listener
            listener = new TcpListener(ipaddress, port);

            // Set loop variable
            Boolean loop = true;
            try
            {
                // Start listening on client port
                listener.Start();

                while (loop)
                {
                    Socket newClient = listener.AcceptSocket();
                    ClientThreadHandler cth = new ClientThreadHandler(newClient);
                    cth.StartHandling();
                }
            }catch(Exception error)
            {
                MessageBox.Show(error.Message);
            }
        }
예제 #20
0
        public void Connect()
        {
            _listener = new TcpListener(IPAddress.Any, 51414);
            _listener.Start();
            Boolean cancel = false;

            while (!cancel)
            {
                {

                   Socket s = _listener.AcceptSocket();
                     lock (Clients)
                     {
                    BackgroundWorker clientListenerWorker = new BackgroundWorker();
                    ISocketListener clientListener = _appcontext.
                                                        GetObject<ISocketListener>();
                    ITypeTranslator translator = _appcontext.
                                                        GetObject<ITypeTranslator>();
                    IEnumerable<IModuleHandler> modules = _appcontext.
                                                        GetAllObjects<IModuleHandler>();
                    clientListenerWorker.DoWork += new DoWorkEventHandler(clientListener.Start);
                    clientListenerWorker.RunWorkerAsync(s);

                    BackgroundWorker clientIsAliveWorker = new BackgroundWorker();

                    }

                }
            }
        }
예제 #21
0
        static void ListenerThreadEntry()
        {
            try
            {
                var listener = new TcpListener(IPAddress.Any, Port);
                listener.Start();

                using (var socket = listener.AcceptSocket())
                {
                    var serverCertificate = new X509Certificate2(CertsPath + @"\test.pfx");
                    var stream = new NetworkStream(socket);
                    using (var sslStream = new SslStream(stream, false))
                    {
                        sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, false);

                        // terminate the connection
                        sslStream.Close();
                        socket.Disconnect(false);
                        socket.Close();

                        // this code will fail
                        using (var reader = new StreamReader(sslStream))
                        {
                            var line = reader.ReadLine();
                            Console.WriteLine("> " + line);
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc);
            }
        }
예제 #22
0
        public override void startListening()
        {
            while(!Stop) {
                try {
                    imageDelay = 1000;
                    listener = new TcpListener(this.GivenIPAddress, this.StartingPort);
                    listener.Start();
                    mainSocket = listener.AcceptSocket();
                    s = new NetworkStream(mainSocket);
                    while(true) {
                        Bitmap screeny = new Bitmap(InvokerForm.Width, InvokerForm.Height, PixelFormat.Format32bppArgb);
                        Graphics theShot = Graphics.FromImage(screeny);
                        theShot.ScaleTransform(.25F, .25F);
                        theShot.CopyFromScreen(InvokerForm.Left, InvokerForm.Top, 0, 0, InvokerForm.Size, CopyPixelOperation.SourceCopy);
                        BinaryFormatter bFormat = new BinaryFormatter();
                        bFormat.Serialize(s, screeny);

                        Thread.Sleep(imageDelay);
                        theShot.Dispose();
                        screeny.Dispose();
                    }
                }

                catch(Exception) {
                    if(mainSocket.IsBound)
                        mainSocket.Close();
                    if(listener != null)
                        listener.Stop();
                }
            }
        }
예제 #23
0
		private static void RunServer(int port)
		{
			TcpListener serverSocket = new TcpListener(IPAddress.Parse("127.0.0.1"), port);
			serverSocket.Start();

			new System.Threading.Thread(() => {
				while (true) {
					var clientSocket = serverSocket.AcceptSocket();
					if (clientSocket != null) {
						Console.Error.WriteLine(">> accepted connection from client");

						new System.Threading.Thread(() => {
							using (var networkStream = new NetworkStream(clientSocket)) {
								try {
									Dispatch(networkStream, networkStream);
								}
								catch (Exception e) {
									Console.Error.WriteLine("Exception: " + e);
								}
							}
							#if DNXCORE50
							clientSocket.Dispose();
							#else
							clientSocket.Close();
							#endif
							Console.Error.WriteLine(">> client connection closed");
						}).Start();
					}
				}
			}).Start();
		}
예제 #24
0
 private void StartListen2()
 {
     //Create an instance of TcpListener to listen for TCP connection.
     var tcpListener = new TcpListener(SampleTcpPort);
     try
     {
         while (true)
         {
             tcpListener.Start();
             //Program blocks on Accept() until a client connects.
             Socket soTcp = tcpListener.AcceptSocket();
             Console.Message = ("SampleClient is connected through TCP.");
             OnChanged(EventArgs.Empty);
             var received = new Byte[512];
             soTcp.Receive(received, received.Length, 0);
             String dataReceived = System.Text.Encoding.ASCII.GetString(received);
             Console.Message=(dataReceived);
             String returningString = "The Server got your message through TCP: " +
                                      dataReceived; OnChanged(EventArgs.Empty);
             Byte[] returningByte = System.Text.Encoding.ASCII.GetBytes
                 (returningString.ToCharArray());
             //Returning a confirmation string back to the client.
             soTcp.Send(returningByte, returningByte.Length, 0);
         }
     }
     catch (SocketException se)
     {
         Console.Message = ("A Socket Exception has occurred!" + se); OnChanged(EventArgs.Empty);
     }
 }
예제 #25
0
        public void StartServer()
        {
            TcpListener server = new TcpListener(IPAddress.Parse("192.168.0.13"), 14500);

            server.Start();
            Console.WriteLine("Server has started on 127.0.0.1:14500.{0}Waiting for a connection...", Environment.NewLine);

            while (true)
            {
                Socket client = server.AcceptSocket();

                Console.WriteLine("A client connected.");

                var childSocketThread = new Thread(() =>
                {
                    byte[] data = new byte[4096];
                    int size = client.Receive(data);
                    if (size > 4096) //the packet is too god damn high
                    {
                        Console.Write("Client tried to send packet above 4096 bytes");
                        return;
                    }
                    HandlePacket(client,data);
                    Console.WriteLine("Recieved data:");
                    for (int i = 0; i < size; i++)
                    {
                        Console.Write(Convert.ToChar(data[i]));
                    }
                    Console.WriteLine();
                    client.Close();
                });

                childSocketThread.Start();
            }
        }
예제 #26
0
        static void BackupProcess()
        {
            Console.WriteLine("I am backup!");
            
            IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
            TcpListener listener = new TcpListener(ipAddress, port);
            listener.Start();
            Socket sock = listener.AcceptSocket();
            Stream str = new NetworkStream(sock);
            StreamReader sr = new StreamReader(str);

            string line = "-1";

            try
            {
                while (true)
                    line = sr.ReadLine();
            }
            catch(IOException)
            { 
                sr.Close();
                listener.Stop();

                PrimaryProcess(Convert.ToInt32(line) + 1);
            }
        }
예제 #27
0
        public void Run()
        {
            _broadcaster = new Broadcaster();

            IPAddress ip = IPAddress.Parse(_servername);
            TcpListener listener = new TcpListener(ip, _port);

            /* Gør så at serveren kan skrive input*/
            Thread serverInputThread = new Thread(HandleInput);
            serverInputThread.Start();

            _running = true;

            listener.Start();

            Console.WriteLine("Skriv \'new\' for at starte en ny auktion.");

            while (_running)
            {
                System.Console.WriteLine("Server klar til bruger");
                /* En socket forbinder*/
                Socket clientSocket = listener.AcceptSocket();

                /* Lav en ny client handler til forbindelsen */
                ClientHandler handler = new ClientHandler(clientSocket, _broadcaster);
                handler.SetAuction(_auction);

                /* Start det i en ny tråd */
                Thread clientThread = new Thread(handler.RunClient);

                /* Start trådene */
                clientThread.Start();
            }
        }
예제 #28
0
        static void Main(string[] args)
        {
            var settings = ConfigurationManager.AppSettings;
            var port = settings["COM_PORT"];
            var speed = Convert.ToInt32(settings["COM_SPEED"]);
            var tcpPort = Convert.ToInt32(settings["TCP_PORT"]);
            serial = new SerialManager(port, speed);
            Console.WriteLine("UART: " + port + " - " + speed);
            server = new HardwareTcpServer(tcpPort);
            server.OnServerState += server_OnServerState;
            server.OnClientState += server_OnClientState;
            server.OnData += server_OnData;
            serial.OnReceive += serial_OnReceive;
            serial.OnStateChange += serial_OnStateChange;
            serial.Connect();

           // bridge = new HttpToUartBridge(6200);

            TcpListener listener = new TcpListener(IPAddress.Parse("188.127.233.35"), tcpPort);
            listener.Start();
            Console.WriteLine("TCP: " + tcpPort);
            while (Thread.CurrentThread.ThreadState == ThreadState.Running)
            {
                Console.WriteLine("Listening " + tcpPort);
                while (!listener.Pending())
                {
                    Thread.Sleep(300);
                }
                server.AcceptTcpClient(listener.AcceptSocket());
            }
            Console.WriteLine("Stopped");
            listener.Stop();
            server.Close();
            serial.Close();
        }
예제 #29
0
파일: Form1.cs 프로젝트: mayifighting/.net
 public void BeginLister()
 {
     while (true)
     {
         try
         {
             IPAddress[] Ips = Dns.GetHostAddresses("");
             string GetIp = Ips[0].ToString();
             Listener = new TcpListener(IPAddress .Parse (GetIp ),8888);
             Listener.Start();
             CheckForIllegalCrossThreadCalls = false;
             butBeginSever.Enabled = false;
             this.Text = "服务器已经开启.....";
             SocketClient = Listener.AcceptSocket();
             NetStream = new NetworkStream(SocketClient );
             ServerWriter = new StreamWriter(NetStream );
             ServerReader = new StreamReader(NetStream );
             if (SocketClient.Connected)
             {
                 MessageBox.Show("客户端连接成功!","服务器消息",MessageBoxButtons .OK ,MessageBoxIcon.Information );
             }
         }
         catch { }
     }
 }
예제 #30
0
        public static void Start(int port)
        {
            TcpListener listener = new TcpListener (IPAddress.Loopback, port);
            listener.Start ();

            while (run) {
                while (!listener.Pending() && run) {
                    Thread.Sleep (200);
                }

                if (!run)
                    break;

                Socket newSocket = listener.AcceptSocket ();

                Thread thread = new Thread (new ParameterizedThreadStart (Handshaker));

                int id = 0;
                lock (serviceThreads) {
                    id = serviceThreads.Count > 0 ? serviceThreads.Keys.Max () + 1 : 0;
                    serviceThreads.Add (id, thread);
                }

                thread.Start (new object[] { id, newSocket });
            }
        }
예제 #31
0
 void HandleThreadStart()
 {
     try {
         TCL = new System.Net.Sockets.TcpListener(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 10112));
         TCL.Start();
         do
         {
             try {
                 System.Net.Sockets.Socket S = TCL.AcceptSocket();
                 FeuerwehrCloud.Helper.Logger.WriteLine("|  < [FAX] *** Incoming notification");
                 S.Blocking = false;
                 S.BeginReceive(buffer, 0, DEFAULT_SIZE - dataRecieved,
                                System.Net.Sockets.SocketFlags.None, new AsyncCallback(HandleAsyncCallback), S);
                 if (IsTerminating)
                 {
                     break;
                 }
             } catch (Exception e2x) {
             }
         } while (true);
     } catch (Exception ex) {
         if (ex.Message.Contains("already in use"))
         {
             FeuerwehrCloud.Helper.Logger.WriteLine("Kann FeuerwehrCloud-Server FaxModul nicht starten!");
         }
     }
 }
예제 #32
0
        public void FTPSessionThread()
        {
            while (true)
            {
                try
                {
                    // 處理用戶端連線
                    clientSocket = tcpListener.AcceptSocket();

                    // 取得本機相關的網路資訊
                    IPEndPoint serverInfo = (IPEndPoint)tcpListener.LocalEndpoint;

                    // 取得連線用戶端相關的網路連線資訊
                    IPEndPoint clientInfo = (IPEndPoint)clientSocket.RemoteEndPoint;

                    Console.WriteLine("Server: " + serverInfo.Address.ToString() + ":" + serverInfo.Port.ToString());
                    Console.WriteLine("Client: " + clientInfo.Address.ToString() + ":" + clientInfo.Port.ToString());

                    // 執行緒
                    Thread clientThread = new Thread(new ThreadStart(this.processRequest));
                    clientThread.Start();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace.ToString());

                    if (clientSocket.Connected)
                    {
                        clientSocket.Close();
                    }
                }
            }
        }
예제 #33
0
		public void ProcessMessageTest()
		{
			// setup the client configurations
			TcpSendEndpoint sendEndpoint = new TcpSendEndpoint();
			TcpSendOptions options = new TcpSendOptions();
			options.Endpoint = new IPEndPoint(IPAddress.Loopback, 6789);
			sendEndpoint.Initialize(null, options);

			// start a tcp listener
			TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, 6789));
			listener.Start();

			// start the enpoint for processing
			sendEndpoint.StartProcessing();

			// send messages
			byte[] data = { 0x41, 0x41, 0x41, 0x41 };
			sendEndpoint.ProcessMessage(null, data); // AAAA

			// assert listener for receive of messages
			var socket = listener.AcceptSocket();
			byte[] readData = new byte[8];
			Assert.AreEqual(8, socket.Receive(readData, 0, 8, SocketFlags.None));

			// close the client
			sendEndpoint.StopProcessing();

			// close the server
			listener.Stop();

			// assert data is valid

			byte[] expectedData = { TcpSendOptions.SOH, TcpSendOptions.STX, 0x41, 0x41, 0x41, 0x41, TcpSendOptions.ETX, TcpSendOptions.EOT };
			Assert.IsTrue(expectedData.SequenceEqual(readData));
		}
예제 #34
0
        public void ServerThreadProc()
        {
            while (true)
            {
                try
                {
                    // 處理用戶端連線
                    clientSocket = tcpListener.AcceptSocket();

                    // 取得本機相關的網路資訊
                    IPEndPoint serverInfo = (IPEndPoint)tcpListener.LocalEndpoint;

                    // 取得連線用戶端相關的網路連線資訊
                    IPEndPoint clientInfo = (IPEndPoint)clientSocket.RemoteEndPoint;

                    Console.WriteLine("Client: " + clientInfo.Address.ToString() + ":" + clientInfo.Port.ToString());
                    Console.WriteLine("Server: " + serverInfo.Address.ToString() + ":" + serverInfo.Port.ToString());

                    // 設定接收資料緩衝區
                    byte[] bytes = new Byte[1024];

                    // 自已連線的用戶端接收資料
                    int bytesReceived = clientSocket.Receive(bytes, 0, bytes.Length, SocketFlags.None);

                    if (bytesReceived > 0)
                    {
                        Console.WriteLine("接收位元組數目: {0}", bytesReceived);
                        Console.WriteLine("接收的資料內容: \r\n" + "{0}", Encoding.UTF8.GetString(bytes, 0, bytesReceived) + "\r\n");
                    }

                    // 測試用
                    string htmlBody   = "<html><head><title>Send Test</title></head><body><font size=2 face=Verdana>Sent OK.</font></body></html>";
                    string htmlHeader = "HTTP/1.0 200 OK" + "\r\n" + "Server: HTTP Server 1.0" + "\r\n" + "Content-Type: text/html" + "\r\n" + "Content-Length: " + htmlBody.Length + "\r\n\r\n";

                    string htmlContent = htmlHeader + htmlBody;

                    // 設定傳送資料緩衝區
                    byte[] msg = Encoding.ASCII.GetBytes(htmlContent);

                    // 傳送資料至已連線的用戶端
                    int bytesSend = clientSocket.Send(msg, 0, msg.Length, SocketFlags.None);

                    Console.WriteLine("傳送位元組數目: {0}", bytesSend);
                    Console.WriteLine("傳送的資料內容: " + "\r\n" + "{0}", Encoding.UTF8.GetString(msg, 0, bytesSend) + "\r\n");

                    // 同時暫停用戶端的傳送和接收作業
                    clientSocket.Shutdown(SocketShutdown.Both);
                    // 關閉用戶端Socket
                    clientSocket.Close();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace.ToString());
                }
            }
        }
예제 #35
0
 //private NetworkStream stream;
 //private float nextSendTime = 0.0f;
 // Use this for initialization
 void Start()
 {
     //server.BeginAcceptSocket (connection_made, null);
     System.Net.IPAddress addr;        // = new System.Net.IPAddress();
     addr = System.Net.IPAddress.Parse("127.0.0.1");
     System.Net.IPEndPoint ep = new System.Net.IPEndPoint(addr, 8000);
     server = new TcpListener(ep);
     server.Start();
     Debug.Log("Waiting for socket to connect");
     connectionSocket = server.AcceptSocket();
     Debug.Log("Connected!");
     connected = true;
     StartCoroutine(send_frame());
 }
예제 #36
0
파일: Program.cs 프로젝트: aooshi/adf.cs
        static void Server()
        {
            var tcpListener = new System.Net.Sockets.TcpListener(IPAddress.Any, port);

            tcpListener.Start();

            System.Threading.ThreadPool.QueueUserWorkItem(sta =>
            {
                var socket = tcpListener.AcceptSocket();
                //
                var state    = new ServerSocketState();
                state.socket = socket;
                state.buffer = new byte[1];
                //
                socket.BeginReceive(state.buffer, 0, state.buffer.Length, System.Net.Sockets.SocketFlags.None, ServerCallback, state);
            });
        }
예제 #37
0
        void HandleThreadStart()
        {
            try {
                TCL = new System.Net.Sockets.TcpListener(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 20112));
                TCL.Start();
                do
                {
                    System.Net.Sockets.Socket S = TCL.AcceptSocket();
                    FeuerwehrCloud.Helper.Logger.WriteLine("|  < [Probealarm] *** Incoming Probealarm");

                    if (!System.IO.File.Exists("/tmp/probealarm.png"))
                    {
                        try {
                            System.IO.File.Copy("probealarm.png", "/tmp/probealarm.png", true);
                        } catch (Exception ex) {
                            FeuerwehrCloud.Helper.Logger.WriteLine("[Probealarm] " + FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex));
                        }
                    }

                    // Notify running Display-Software!
                    new System.Threading.Thread(delegate() {
                        try {
                            System.Net.Sockets.TcpClient TC = new TcpClient();
                            TC.Connect("localhost", 27655);
                            TC.GetStream().Write(System.Text.Encoding.Default.GetBytes("GET / HTTP/1.0\r\n\r\n"), 0, 18);
                            TC.Close();
                        } catch (Exception ex) {
                            FeuerwehrCloud.Helper.Logger.WriteLine("[Probealarm] " + FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex));
                        }
                    }).Start();

                    try {
                        S.BeginReceive(buffer, dataRecieved, DEFAULT_SIZE - dataRecieved,
                                       System.Net.Sockets.SocketFlags.None, new AsyncCallback(HandleAsyncCallback), S);
                    } catch (Exception ex) {
                        FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex));
                    }
                } while (true);
            } catch (Exception ex) {
                if (ex.Message.Contains("already in"))
                {
                    FeuerwehrCloud.Helper.Logger.WriteLine("Kann FeuerwehrCloud-Server Probealarm-Modul nicht starten!");
                }
            }
        }
예제 #38
0
 public void Start()
 {
     Started = ServerStatus.Running;
     _tcpListener.Start();
     new Thread(() => {
         while (Started == ServerStatus.Running)
         {
             try
             {
                 var socket = _tcpListener.AcceptSocket();
                 this.handleSocket(socket);
             }
             catch
             {
             }
         }
     }).Start();
 }
예제 #39
0
        public void ServerThreadProc()
        {
            while (true)
            {
                try
                {
                    // 處理用戶端連線
                    clientSocket = tcpListener.AcceptSocket();

                    // 取得本機相關的網路資訊
                    IPEndPoint serverInfo = (IPEndPoint)tcpListener.LocalEndpoint;

                    // 取得連線用戶端相關的網路連線資訊
                    IPEndPoint clientInfo = (IPEndPoint)clientSocket.RemoteEndPoint;

                    Console.WriteLine("Client: " + clientInfo.Address.ToString() + ":" + clientInfo.Port.ToString());
                    Console.WriteLine("Server: " + serverInfo.Address.ToString() + ":" + serverInfo.Port.ToString());
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.StackTrace.ToString());
                }
            }
        }
예제 #40
0
        void HandleThreadStart()
        {
            try {
                TCL = new System.Net.Sockets.TcpListener(new System.Net.IPEndPoint(System.Net.IPAddress.Any, 30112));
                TCL.Start();
                do
                {
                    System.Net.Sockets.Socket S = TCL.AcceptSocket();
                    FeuerwehrCloud.Helper.Logger.WriteLine("|  < [DEMO-Alarm] *** Incoming DEMO-Alarm");

                    try {
                        S.BeginReceive(buffer, dataRecieved, DEFAULT_SIZE - dataRecieved,
                                       System.Net.Sockets.SocketFlags.None, new AsyncCallback(HandleAsyncCallback), S);
                    } catch (Exception ex) {
                        FeuerwehrCloud.Helper.Logger.WriteLine(FeuerwehrCloud.Helper.Helper.GetExceptionDescription(ex));
                    }
                } while (true);
            } catch (Exception ex) {
                if (ex.Message.Contains("already in"))
                {
                    FeuerwehrCloud.Helper.Logger.WriteLine("Kann DEMO-Port nicht binden - Läuft der FeuerwehrCloud-Server bereits?");
                }
            }
        }