Esempio n. 1
0
        /// <summary>
        /// Open 通信要求受付(非同期)
        /// </summary>
        /// <param name="ipAddr">IPアドレス</param>
        /// <param name="ipPort">ポート</param>
        /// <returns></returns>
        public async void OpenAsync()
        {
            sw.Start();

            //ListenするIPアドレス
            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(listenIP);

            //TcpListenerオブジェクトを作成する
            listener =
                new System.Net.Sockets.TcpListener(ipAdd, listenPort);

            //Listenを開始する
            listener.Start();
            Console.WriteLine("Listenを開始しました({0}:{1})。",
                ((System.Net.IPEndPoint)listener.LocalEndpoint).Address,
                ((System.Net.IPEndPoint)listener.LocalEndpoint).Port);

            //接続要求があったら受け入れる
            //client = listener.AcceptTcpClient();
            try
            {
                client = await listener.AcceptTcpClientAsync();
                Console.WriteLine("クライアント({0}:{1})と接続しました。",
                    ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address,
                    ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port);

                //NetworkStreamを取得
                ns = client.GetStream();
            }
            catch (Exception)
            {
            }
        }
Esempio n. 2
0
        public DemoChatServer()
        {
            try
            {
                //create our TCPListener object
                chatServer = new System.Net.Sockets.TcpListener(IPAddress.Any, 4296);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            Console.WriteLine("DemoChat server started.");
            //while (true) do the commands

            while (true)
            {
                //start the chat server
                chatServer.Start();

                //check if there are any pending connection requests
                if (chatServer.Pending())
                {
                    //if there are pending requests create a new connection
                    System.Net.Sockets.TcpClient chatConnection = chatServer.AcceptTcpClient();

                    //display a message letting the user know they're connected
                    Console.WriteLine("New connection from: " + GetRemoteIPAddress(chatConnection));

                    //create a new DoCommunicate Object
                    ChatConnection con = new ChatConnection(chatConnection);
                }
            }
        }
Esempio n. 3
0
        public void Accept()
        {
            closed = false;
            try
            {
                if (serverSocket == null)
                {
                    //commented by shariq
                    //temp_tcpListener = new System.Net.Sockets.TcpListener(System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName()).AddressList[0], port);
                    //listen on all adapters
                    var temp_tcpListener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Parse("0.0.0.0"), port);

                    temp_tcpListener.Start();
                    serverSocket = temp_tcpListener;
                }
                while (true)
                {
                    var socket = serverSocket.AcceptTcpClient();
                    connectionListener.OnConnect(new TcpConnection(socket));
                }
            }
            catch (System.IO.IOException e)
            {
                if (!closed)
                    throw new FastConnectionException(e);
            }
        }
Esempio n. 4
0
        public static void ListenTCP()
        {
            if (!Configuration.TCP)
            {
                return;
            }
            try
            {
                MainClass.DebugLog("Listening on TCP port " + Configuration.Port);
                System.Net.Sockets.TcpListener server = new System.Net.Sockets.TcpListener(IPAddress.Any, Configuration.Port);
                server.Start();

                while(MainClass.isRunning)
                {
                    try
                    {
                        System.Net.Sockets.TcpClient connection = server.AcceptTcpClient();
                        Thread _client = new Thread(HandleClient);
                        _client.Start(connection);

                    } catch (Exception fail)
                    {
                        MainClass.exceptionHandler(fail);
                    }
                }
            } catch (Exception fail)
            {
                MainClass.exceptionHandler(fail);
            }
        }
Esempio n. 5
0
 public ChatServer()
 {
     //create our nickname and nickname by connection variables
     nickName = new Hashtable(100);
     nickNameByConnect = new Hashtable(100);
     //create our TCPListener object
     chatServer = new System.Net.Sockets.TcpListener(new IPEndPoint(IPAddress.Any, 23));
     //check to see if the server is running
     //while (true) do the commands
     while (true)
     {
         //start the chat server
         chatServer.Start();
         //check if there are any pending connection requests
         if (chatServer.Pending())
         {
             //if there are pending requests create a new connection
             Chat.Sockets.TcpClient chatConnection = chatServer.AcceptTcpClient();
             //display a message letting the user know they're connected
             Console.WriteLine("You are now connected");
             //create a new DoCommunicate Object
             DoCommunicate comm = new DoCommunicate(chatConnection);
         }
     }
 }
Esempio n. 6
0
        public static void Main(string[] args)
        {
            Console.WriteLine ("Eve Emulation Server Initialized.");
            System.Net.Sockets.TcpListener listen = new System.Net.Sockets.TcpListener (IPAddress.Loopback, 26000);
            listen.Start ();
            Console.Write ("Now listening on ");
            Console.Write (IPAddress.Loopback.ToString ());
            Console.WriteLine (":26000");
            while (!listen.Pending())
                continue;
            var eveClient = listen.AcceptTcpClient ();
            Console.WriteLine ("Connected.");
            Console.WriteLine("Handshaking...");
            var SendBuffer = System.Text.UTF8Encoding.UTF8.GetBytes("Hello!");
            eveClient.GetStream().Write(SendBuffer, 0, SendBuffer.Length);
            while (eveClient.Client.Available <= 0)
                continue;
            Console.WriteLine ("Got Stream");
            byte[] buffer = new byte[1024];
            int lengthFix = 0;
            var stream = eveClient.GetStream ();
            List<byte> RawListOfBytes = new List<byte>();
            do
            {
                lengthFix = stream.Read(buffer, 0, buffer.Length);
                Array.Resize(ref buffer, lengthFix);
                RawListOfBytes.AddRange(buffer);
                buffer = new byte[1024];

            } while (lengthFix > 0);
            Console.WriteLine("Output:");
            Console.WriteLine("");
            Console.Write (BitConverter.ToString(RawListOfBytes.ToArray()));
            Console.ReadLine();
        }
 public static int GetRandomUnusedPort()
 {
     System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, 0);
     listener.Start();
     int port = ((System.Net.IPEndPoint)listener.LocalEndpoint).Port;
     listener.Stop();
     return port;
 } // End Function GetRandomUnusedPort 
Esempio n. 8
0
 private static int FreeTcpPort()
 {
   var l = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
   l.Start();
   var port = ((System.Net.IPEndPoint)l.LocalEndpoint).Port;
   l.Stop();
   return port;
 }
Esempio n. 9
0
 public MsgSource(int port)
 {
   this.port = port;
   Console.Write("Listening...");
   server = System.Net.Sockets.TcpListener.Create(port);
   server.Start();
   serverside_client = server.AcceptTcpClient();
   Console.WriteLine("\nClient connected");
   stream = serverside_client.GetStream();
 }
Esempio n. 10
0
        //通信開始ボタン(待機状態に)
        private void button1_Click(object sender, EventArgs e)
        {
            if (socet == false)//つながってないなら
            {
                try
                {
                    //ListenするIPアドレス
                    //string ipString = "127.0.0.1";
                    string ipString = textBox3.Text;
                    System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString);

                    //ホスト名からIPアドレスを取得する時は、次のようにする
                    //string host = "localhost";
                    //System.Net.IPAddress ipAdd =
                    //    System.Net.Dns.GetHostEntry(host).AddressList[0];
                    //.NET Framework 1.1以前では、以下のようにする
                    //System.Net.IPAddress ipAdd =
                    //    System.Net.Dns.Resolve(host).AddressList[0];

                    //Listenするポート番号
                    int port = int.Parse(textBox4.Text);

                    //TcpListenerオブジェクトを作成する
                    listener = new System.Net.Sockets.TcpListener(ipAdd, port);

                    //Listenを開始する
                    listener.Start();
                    label1.Text = "Listenを開始しました(" + ((System.Net.IPEndPoint)listener.LocalEndpoint).Address + ":" + ((System.Net.IPEndPoint)listener.LocalEndpoint).Port + ")。";

                    //接続要求があったら受け入れる
                    client = listener.AcceptTcpClient();
                    label1.Text = "クライアント(" + ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address + ":" + ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port + ")と接続しました。";

                    //NetworkStreamを取得
                    ns = client.GetStream();

                    //読み取り、書き込みのタイムアウトを10秒にする
                    //デフォルトはInfiniteで、タイムアウトしない
                    //(.NET Framework 2.0以上が必要)
                    ns.ReadTimeout = 10000;
                    ns.WriteTimeout = 10000;
                    socet = true;
                }
                catch (FormatException)
                {
                    MessageBox.Show("IPアドレス、ポート番号を正しく入力してください(半角)", "エラー");
                }
                catch (System.Net.Sockets.SocketException ER)
                {
                    MessageBox.Show("IPアドレスが間違ってます。\ncmd.exeで調べてください\n(ipconfig)", "エラー");
                }
            }

           
        }
Esempio n. 11
0
		/// <summary>
		/// This method runs TCP/IP listener, waits for the connected client and set the closing actions for client and server after the competitions are over.
		/// </summary>
		/// <param name="data"></param>
		public void RunServer(NetworkServerData data)
		{
			var server = new System.Net.Sockets.TcpListener(data.Port);
			server.Start();
			data.ServerLoaded = true;
			var client = server.AcceptTcpClient();
			data.ClientOnServerSide = new CvarcClient(client);
			data.StopServer = () =>
			{
				client.Close();
				server.Stop();
			};
		}
        static void Main(string[] args)
        {
            t = new System.Timers.Timer();
            t.Interval = 1000;
            t.Elapsed += T_Elapsed;

            try
            {
                System.Net.IPAddress IP = System.Net.IPAddress.Parse("192.168.3.22");
                System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(IP, 1955);
                Console.WriteLine("\rPackets Recd: ");
                Console.WriteLine("\rTime: " + " Seconds");
                Console.WriteLine("\rMoving Avg:\t  Bytes/sec");
                Console.WriteLine("\rTotal Avg:\t  Bytes/sec");
                Console.WriteLine("\rMax:\t Bytes/sec");
                Console.WriteLine("\rMin:\t Bytes/sec");
                listener.Start();
                while (true)
                {
                    System.Net.Sockets.Socket client = listener.AcceptSocket();
                    Console.WriteLine("Connection accepted.");
                    startTime = DateTime.Now;
                    bytesRec = 0;
                    t.Start();
                    var childSocketThread = new Thread(() =>
                    {
                        while (client.Connected == true)
                        {
                            byte[] data = new byte[1000];
                            int size = client.Receive(data);
                            bytesRec += uint.Parse(size.ToString());
                            /*                            Console.WriteLine("Recieved data: ");
                                                        for (int i = 0; i < size; i++)
                                                            Console.Write(Convert.ToChar(data[i]));
                                                      Console.WriteLine(); */

                        }
                        client.Close();
                    });
                    childSocketThread.Start();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("FATAL EXCEPTION!");
                Console.WriteLine(ex.Message);
                Console.WriteLine("Press enter to exit");
                Console.ReadLine();
            }
        }
Esempio n. 13
0
		private void ThreadRun()
		{
			m_socketListen = Assemblies.General.SocketHelpers.CreateTcpListener(m_nPort);

			if (m_socketListen != null)
			{			
				m_socketListen.Start();

				FtpServerMessageHandler.SendMessage(0, "FTP Server Started");

				bool fContinue = true;

				while (fContinue)
				{
					System.Net.Sockets.TcpClient socket = null;

					try
					{
						socket = m_socketListen.AcceptTcpClient();
					}
					catch (System.Net.Sockets.SocketException)
					{
						fContinue = false;
					}
					finally
					{
						if (socket == null)
						{
							fContinue = false;
						}
						else
						{
							socket.NoDelay = false;

							m_nId ++;

							FtpServerMessageHandler.SendMessage(m_nId, "New connection");

							SendAcceptMessage(socket).Wait();
							InitialiseSocketHandler(socket);
						}
					}
				}
			}
			else
			{
				FtpServerMessageHandler.SendMessage(0, "Error in starting FTP server");
			}
		}
    public bool SetupListen(int port)
    {
        // Set the TcpListener on port 13000.
        //Int32 port = 13000;
        System.Net.IPAddress localAddr = System.Net.IPAddress.Parse("127.0.0.1");
        //IPAddress localAddr = Dns.Resolve("localhost").AddressList[0];

        //serverSocket = new TcpListener(port);	// This is obsolete!
        serverSocket = new System.Net.Sockets.TcpListener(localAddr, port);

        // Start listening for client requests.
        serverSocket.Start();

        return true;
    }
Esempio n. 15
0
 public void Start_passes_if_at_least_one_nic_is_free()
 {
     var listener = new System.Net.Sockets.TcpListener(new IPAddress(new byte[] { 127, 0, 0, 1 }), _serverPort);
     listener.Start();
     try
     {
         var server = new SimpleTcpServer().Start(_serverPort);
         Assert.IsTrue(server.IsStarted, "Server should have started on free nics");
         server.Stop();
     }
     finally
     {
         listener.Stop();
     }
 }
        public void listen()
        {
            //System.Net.IPAddress ip = System.Net.IPAddress.Parse(IP_add);
            listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, port);
            System.Console.WriteLine("Port:{0}", port);

            listener.Start();

            System.Net.Sockets.TcpClient client = listener.AcceptTcpClient();
            System.Console.WriteLine("connect");

            ns = client.GetStream();
            ns.ReadTimeout = 10000;
            ns.WriteTimeout = 10000;
            System.Console.WriteLine("connect2");
        }
Esempio n. 17
0
 private static int GetFreeTcpPort(int port)
 {
     for (; ; )
     {
         try
         {
             System.Net.Sockets.TcpListener tcpListener = new System.Net.Sockets.TcpListener(IPAddress.Any, port);
             tcpListener.Start();
             tcpListener.Stop();
             break;
         }
         catch (System.Net.Sockets.SocketException)
         {
             port--;
         }
     }
     return port;
 }
Esempio n. 18
0
        /// <summary>
        /// Attempts to start TCP server at given port
        /// </summary>
        /// <param name="nPort"></param>
        /// <returns></returns>
        public bool bind(int nPort)
        {
            m_pTcpListener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, nPort);
            m_pWorkerThead = new System.Threading.Thread(workerThread);
            m_pClientList = new List<Objects.Client>();

            try
            {
                m_pTcpListener.Start(64);
                m_pWorkerThead.Start();
            }
            catch
            {
                return false;
            }

            return true;
        }
Esempio n. 19
0
File: Program.cs Progetto: vebin/BD2
        public static void Main(string[] args)
        {
            Console.Write ("Please Enter Operation Mode <Client|Server>: ");
            string modeName = ConsoleReadLine ();
            Guid ChatServiceAnouncementType = Guid.Parse ("b0021151-a1cc-4f82-aa8d-a2cdb905e6ca");

            if (modeName == "Server") {
                System.Net.Sockets.TcpListener TL = new System.Net.Sockets.TcpListener (new System.Net.IPEndPoint (System.Net.IPAddress.Parse ("0.0.0.0"), 28000));
                TL.Start ();
                while (true)
                    HandleConnection (modeName, ChatServiceAnouncementType, TL.AcceptTcpClient ());
            }
            if (modeName == "Client") {
                System.Net.Sockets.TcpClient TC = null;
                TC = new System.Net.Sockets.TcpClient ();
                Console.Write ("Please Enter Remote IP: ");
                TC.Connect (new System.Net.IPEndPoint (System.Net.IPAddress.Parse (ConsoleReadLine ()), 28000));
                HandleConnection (modeName, ChatServiceAnouncementType, TC);
            }
        }
Esempio n. 20
0
File: Program.cs Progetto: vebin/BD2
        public static void Main(string[] args)
        {
            Console.Write ("Please Enter Operation Mode <Client|Server>: ");
            string modeName = ConsoleReadLine ();

            Guid fileShareServiceAnouncementType = Guid.Parse ("d44568fe-2bbb-4e4b-8aa8-3fb07dc86178");
            if (modeName == "Server") {
                System.Net.Sockets.TcpListener TL = new System.Net.Sockets.TcpListener (new System.Net.IPEndPoint (System.Net.IPAddress.Parse ("0.0.0.0"), 28000));
                TL.Start ();
                while (true)
                    HandleConnection (modeName, fileShareServiceAnouncementType, TL.AcceptTcpClient ());
            }
            if (modeName == "Client") {
                System.Net.Sockets.TcpClient TC = null;
                TC = new System.Net.Sockets.TcpClient ();
                Console.Write ("Please Enter Remote IP: ");
                TC.Connect (new System.Net.IPEndPoint (System.Net.IPAddress.Parse (ConsoleReadLine ()), 28000));
                HandleConnection (modeName, fileShareServiceAnouncementType, TC);
            }
        }
Esempio n. 21
0
		bool Start(Uri.Endpoint endPoint, Action<Action> run)
		{
			bool result;
			if (result = (this.tcpListener = this.Connect(endPoint)).NotNull())
			{
				this.Endpoint = endPoint;
				this.tcpListener.Start();
				run(() => 
				{
					try
					{
						this.OnConnect(Connection.Connect(this.tcpListener.AcceptTcpClient()));
					}
					catch (System.Net.Sockets.SocketException)
					{
						if (this.listener.NotNull())
							this.listener.Abort();
					}
				});
			}
			return result;
		}
Esempio n. 22
0
		private void InitServer()
		{
			this.bases = new System.Collections.Hashtable();
			this.connectionManagers = new System.Collections.Hashtable();
			try
			{
				socketServer = new System.Net.Sockets.TcpListener(port);
				isRunning = true;
			}
			catch (Java.Net.BindException e1)
			{
				isRunning = false;
				throw new NeoDatis.Odb.ODBRuntimeException(NeoDatis.Odb.Core.Error.ClientServerPortIsBusy
					.AddParameter(port), e1);
			}
			catch (System.IO.IOException e2)
			{
				isRunning = false;
				throw new NeoDatis.Odb.ODBRuntimeException(NeoDatis.Odb.Core.Error.ClientServerCanNotOpenOdbServerOnPort
					.AddParameter(port), e2);
			}
		}
Esempio n. 23
0
		/// <summary> Loop that waits for a connection and starts a ConnectionManager
		/// when it gets one.
		/// </summary>
		public override void  Run()
		{
			try
			{
				System.Net.Sockets.TcpListener temp_tcpListener;                
				temp_tcpListener = new System.Net.Sockets.TcpListener(System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[0], port);
				temp_tcpListener.Start();
                ss = temp_tcpListener;
				while (keepRunning())
				{
					try
					{                        
						System.Net.Sockets.TcpClient newSocket = ss.AcceptTcpClient();						
						NuGenConnection conn = new NuGenConnection(parser, this.llp, newSocket);
						newConnection(conn);
					}
					catch (System.IO.IOException)
					{
						//ignore - just timed out waiting for connection
					}
					catch (System.Exception)
					{
					}
				}
				
				ss.Stop();
			}
			catch (System.Exception)
			{
			}
			finally
			{
				//Bug 960113:  Make sure HL7Service.stop() is called to stop ConnectionCleaner thread.
				this.stop();
			}
		}
Esempio n. 24
0
		static void Proxy()
		{
			System.Net.Sockets.TcpListener server = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, 23);
			server.Start();
			while (true)
			{
				Console.Write("Waiting for a connection... ");
				System.Net.Sockets.TcpClient serverConnection = server.AcceptTcpClient();
				System.Net.Sockets.NetworkStream serverStream = serverConnection.GetStream();
				Console.WriteLine("Connected");
				System.Net.Sockets.TcpClient clientConnection = new System.Net.Sockets.TcpClient("192.168.1.101", 23);
				System.Net.Sockets.NetworkStream clientStream = clientConnection.GetStream();

				Parallel.Thread.Start(() =>
				{
					while (serverConnection.Connected && clientConnection.Connected)
					{
						int value = clientStream.ReadByte();
						if (value >= 0)
						{
							Console.WriteLine("< " + value + "\t" + new string((System.Text.Encoding.ASCII.GetChars(new byte[] { (byte)value }))));
							serverStream.WriteByte((byte)value);
						}
					}
				});
				while (serverConnection.Connected && clientConnection.Connected)
				{
					int value = serverStream.ReadByte();
					if (value >= 0)
					{
						Console.WriteLine("> " + value + "\t" + new string((System.Text.Encoding.ASCII.GetChars(new byte[] { (byte)value }))));
						clientStream.WriteByte((byte)value);
					}
				}
			}
		}
Esempio n. 25
0
        //public bool IsConnected { get; set; }


        ////Getting the IP Address of the device fro Android.


        //public string getIPAddress()
        //{
        //    string ipaddress = "";

        //    IPHostEntry ipentry = Dns.GetHostEntry(Dns.GetHostName());

        //    foreach (IPAddress ip in ipentry.AddressList)
        //    {
        //        if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
        //        {
        //            ipaddress = ip.ToString();
        //            break;
        //        }
        //    }
        //    return ipaddress;
        //}



        public async Task ServerConnect()
        {
            int port = 3333;
            //ListenするIPアドレス
            string ipString = "127.0.0.1";

            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString);

            //ホスト名からIPアドレスを取得する時は、次のようにする
            //string host = "localhost";
            //System.Net.IPAddress ipAdd =
            //    System.Net.Dns.GetHostEntry(host).AddressList[0];
            //.NET Framework 1.1以前では、以下のようにする
            //System.Net.IPAddress ipAdd =
            //    System.Net.Dns.Resolve(host).AddressList[0];

            //Listenするポート番号
            //int port = 2001;

            //TcpListenerオブジェクトを作成する
            System.Net.Sockets.TcpListener listener = await Task.Run(() => new System.Net.Sockets.TcpListener(ipAdd, port));

            //Listenを開始する
            listener.Start();
            System.Console.WriteLine("Listenを開始しました({0}:{1})。", ((System.Net.IPEndPoint)listener.LocalEndpoint).Address, ((System.Net.IPEndPoint)listener.LocalEndpoint).Port);

            //接続要求があったら受け入れる
            System.Net.Sockets.TcpClient client = listener.AcceptTcpClient(); System.Console.WriteLine("クライアント({0}:{1})と接続しました。",
                                                                                                       ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address,
                                                                                                       ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port);

            //NetworkStreamを取得
            System.Net.Sockets.NetworkStream ns = client.GetStream();

            //読み取り、書き込みのタイムアウトを10秒にする
            //デフォルトはInfiniteで、タイムアウトしない
            //(.NET Framework 2.0以上が必要)
            ns.ReadTimeout  = 10000;
            ns.WriteTimeout = 10000;

            //クライアントから送られたデータを受信する
            System.Text.Encoding enc = System.Text.Encoding.UTF8;
            bool disconnected        = false;

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            byte[] resBytes           = new byte[256];
            int    resSize            = 0;

            do
            {
                //データの一部を受信する
                resSize = ns.Read(resBytes, 0, resBytes.Length);
                //Readが0を返した時はクライアントが切断したと判断
                if (resSize == 0)
                {
                    disconnected = true;
                    System.Console.WriteLine("クライアントが切断しました。");
                    break;
                }
                //受信したデータを蓄積する
                ms.Write(resBytes, 0, resSize);
                //まだ読み取れるデータがあるか、データの最後が\nでない時は、
                // 受信を続ける
            } while (ns.DataAvailable || resBytes[resSize - 1] != '\n');
            //受信したデータを文字列に変換
            string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);

            ms.Close();
            //末尾の\nを削除
            resMsg = resMsg.TrimEnd('\n');
            System.Console.WriteLine(resMsg);

            if (!disconnected)
            {
                //クライアントにデータを送信する
                //クライアントに送信する文字列を作成
                string sendMsg = resMsg.Length.ToString();
                //文字列をByte型配列に変換
                byte[] sendBytes = enc.GetBytes(sendMsg + '\n');
                //データを送信する
                ns.Write(sendBytes, 0, sendBytes.Length);
                System.Console.WriteLine(sendMsg);
            }

            //閉じる
            ns.Close();
            client.Close();
            System.Console.WriteLine("クライアントとの接続を閉じました。");

            //リスナを閉じる
            listener.Stop();
            System.Console.WriteLine("Listenerを閉じました。");

            System.Console.ReadLine();
        }
Esempio n. 26
0
        private static NuGenTransportLayer getTransport(System.Net.Sockets.TcpListener theServerSocket, System.String theAddress)
        {
            NuGenServerSocketStreamSource ss = new NuGenServerSocketStreamSource(theServerSocket, theAddress);

            return(new NuGenMLLPTransport(ss));
        }
Esempio n. 27
0
        public string strListem()
        {
            m_bRunning = true;

            Byte[] byBuffer = new Byte[256];
            string strData  = null;

            System.Net.Sockets.TcpListener tcplCurrent = null;
            try
            {
                tcplCurrent = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Parse(m_strHost), m_nPort);
            }catch {
                return(mdlConstantes.clsConstantes.RESPONSE_SISCOMENSAGEM_ERROR_CANRUN);
            }
            tcplCurrent.Start();
            while (m_bRunning)
            {
                if (tcplCurrent.Pending())
                {
                    // Command
                    System.Net.Sockets.TcpClient     tcpcCurrent = tcplCurrent.AcceptTcpClient();
                    System.Net.Sockets.NetworkStream nsCurrent   = tcpcCurrent.GetStream();
                    // Send Hello
                    byBuffer = System.Text.Encoding.ASCII.GetBytes(strHello() + System.Environment.NewLine + System.Environment.NewLine);
                    nsCurrent.Write(byBuffer, 0, byBuffer.Length);
                    bool bExit = false;
                    while (!bExit)
                    {
                        int i;
                        try
                        {
                            strData = "";
                            while (strData.IndexOf(System.Environment.NewLine + System.Environment.NewLine) == -1)
                            {
                                if ((i = nsCurrent.Read(byBuffer, 0, byBuffer.Length)) != 0)
                                {
                                    strData = strData + System.Text.Encoding.ASCII.GetString(byBuffer, 0, i);
                                }
                            }
                            strData = strData.Replace(System.Environment.NewLine + System.Environment.NewLine, "");
                        }
                        catch
                        {
                            strData = mdlConstantes.clsConstantes.RESPONSE_SISCOMENSAGEM_ERROR_CONNECTIONPROBLEM;
                        }
                        // Execute Command
                        switch (strData)
                        {
                        // SiscoMensagem
                        case mdlConstantes.clsConstantes.COMMAND_SISCOMENSAGEM_EXIT:
                            bExit   = true;
                            strData = mdlConstantes.clsConstantes.RESPONSE_SISCOMENSAGEM_SUCCESS;
                            break;

                        case mdlConstantes.clsConstantes.COMMAND_SISCOMENSAGEM_STATE:
                            if (m_bRunning)
                            {
                                strData = mdlConstantes.clsConstantes.STATE_RUNNING;
                            }
                            else
                            {
                                strData = mdlConstantes.clsConstantes.STATE_STOPED;
                            }
                            break;

                        case mdlConstantes.clsConstantes.COMMAND_SISCOMENSAGEM_HELP:
                            strData = strHelp();
                            break;

                        case mdlConstantes.clsConstantes.COMMAND_SISCOMENSAGEM_STOP:
                            bExit   = true;
                            strData = strSiscoMensagemStop();
                            break;

                        // ControladoraMensagens
                        case mdlConstantes.clsConstantes.COMMAND_SISCOMENSAGEM_CONTROLADORAMENSAGENS_START:
                            strData = strControladoraMensagensStart();
                            break;

                        case mdlConstantes.clsConstantes.COMMAND_SISCOMENSAGEM_CONTROLADORAMENSAGENS_PAUSE:
                            strData = strControladoraMensagensPause();
                            break;

                        case mdlConstantes.clsConstantes.COMMAND_SISCOMENSAGEM_CONTROLADORAMENSAGENS_CONTINUE:
                            strData = strControladoraMensagensContinue();
                            break;

                        case mdlConstantes.clsConstantes.COMMAND_SISCOMENSAGEM_CONTROLADORAMENSAGENS_STOP:
                            strData = strControladoraMensagensStop();
                            break;

                        case mdlConstantes.clsConstantes.COMMAND_SISCOMENSAGEM_CONTROLADORAMENSAGENS_CLOSE:
                            strData = strControladoraMensagensClose();
                            break;

                        case mdlConstantes.clsConstantes.COMMAND_SISCOMENSAGEM_CONTROLADORAMENSAGENS_STATE:
                            strData = strControladoraMensagensState();
                            break;

                        case mdlConstantes.clsConstantes.COMMAND_SISCOMENSAGEM_CONTROLADORAMENSAGENS_UPDATE:
                            strData = strControladoraMensagensUpdate();
                            break;

                        default:
                            strData = mdlConstantes.clsConstantes.RESPONSE_SISCOMENSAGEM_ERROR_UNKNOWCOMMAND;
                            break;
                        }
                        // Response
                        byBuffer = System.Text.Encoding.ASCII.GetBytes(strData + System.Environment.NewLine + System.Environment.NewLine);
                        nsCurrent.Write(byBuffer, 0, byBuffer.Length);
                    }
                    nsCurrent.Close();
                    tcpcCurrent.Close();
                }
                else
                {
                    System.Windows.Forms.Application.DoEvents();
                    System.Threading.Thread.Sleep(m_nSleep);
                }
            }
            tcplCurrent.Stop();
            return(mdlConstantes.clsConstantes.RESPONSE_SISCOMENSAGEM_SUCCESS);
        }
Esempio n. 28
0
        public static void  Main(System.String[] args)
        {
            if (args.Length < 1 || args.Length > 3)
            {
                System.Console.Out.WriteLine("Usage: HL7Server (shared_port | (locally_driven_port remotely_driven_port)) app_binding_URL");
                System.Environment.Exit(1);
            }

            NuGenSafeStorage       storage = new NuGenNullSafeStorage();
            NuGenApplicationRouter router  = new NuGenApplicationRouterImpl();

            try
            {
                NuGenHL7Server server = null;
                System.String  appURL = null;
                if (args.Length == 2)
                {
                    int port = System.Int32.Parse(args[0]);
                    System.Net.Sockets.TcpListener temp_tcpListener;
                    temp_tcpListener = new System.Net.Sockets.TcpListener(System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[0], port);
                    temp_tcpListener.Start();
                    server = new NuGenHL7Server(temp_tcpListener, router, storage);
                    appURL = args[1];
                }
                else
                {
                    int localPort  = System.Int32.Parse(args[0]);
                    int remotePort = System.Int32.Parse(args[1]);
                    System.Net.Sockets.TcpListener temp_tcpListener2;
                    temp_tcpListener2 = new System.Net.Sockets.TcpListener(System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[0], localPort);
                    temp_tcpListener2.Start();
                    System.Net.Sockets.TcpListener temp_tcpListener3;
                    temp_tcpListener3 = new System.Net.Sockets.TcpListener(System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[0], remotePort);
                    temp_tcpListener3.Start();
                    server = new NuGenHL7Server(temp_tcpListener2, temp_tcpListener3, router, storage);
                    appURL = args[2];
                }

                NuGenApplicationLoader.loadApplications(router, getURL(appURL));

                server.start(null);                 //any address OK
            }
            catch (System.FormatException)
            {
                System.Console.Out.WriteLine("Port arguments must be integers");
                System.Environment.Exit(2);
            }
            catch (System.IO.IOException e)
            {
                SupportClass.WriteStackTrace(e, Console.Error);
                System.Environment.Exit(3);
            }
            catch (NuGenHL7Exception e)
            {
                SupportClass.WriteStackTrace(e, Console.Error);
                System.Environment.Exit(4);
            }
            catch (System.UnauthorizedAccessException e)
            {
                SupportClass.WriteStackTrace(e, Console.Error);
                System.Environment.Exit(7);
            }
        }
Esempio n. 29
0
        protected internal async void Listen()  // прослушивание входящих подключений
        {
            System.Net.Sockets.TcpListener tcpListener = System.Net.Sockets.TcpListener.Create(Form1.myForm.LocalHost.intPortChat);
            try
            {
                tcpListener.Start();
                while (true)
                {
                    using (var tcpClient = await tcpListener.AcceptTcpClientAsync())
                    {
                        string id = Guid.NewGuid().ToString();   // id connection
                        // Form1.myForm._richTextBoxEchoAdd( DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " + "Client has connected " + id);

                        using (var networkStream = tcpClient.GetStream())
                        {
                            var buffer    = new byte[4096];
                            var byteCount = await networkStream.ReadAsync(buffer, 0, buffer.Length);

                            var message = encryptDecrypt.DecryptRijndael(Encoding.UTF8.GetString(buffer, 0, byteCount), salt);
                            try { cts.Cancel(); } catch { }
                            try
                            {
                                if (Form1.myForm.RemoteHost.HostName == null)
                                {
                                    try { Form1.myForm.RemoteHost.HostName = System.Net.Dns.GetHostEntry(message.Split('(')[0].Trim()); } catch { }
                                    try { Form1.myForm.RemoteHost.ipAddress = System.Net.IPAddress.Parse((message.Split('(')[1]).Split(')')[0].Trim()); } catch { }
                                    try { Form1.myForm.RemoteHost.intPortGetFile = Convert.ToInt32(message.Split(':')[2].Trim()); } catch { }
                                    Form1.myForm.RemoteHost.SetInfo();
                                }
                                else if (Form1.myForm.RemoteHost.HostName != null)
                                {
                                    string currentIP = (message.Split('(')[1]).Split(')')[0].Trim();
                                    if (currentIP != Form1.myForm.RemoteHost.ipAddress.ToString())
                                    {
                                        try { Form1.myForm.RemoteHost.HostName = System.Net.Dns.GetHostEntry(message.Split('(')[0].Trim()); } catch { }
                                        try { Form1.myForm.RemoteHost.ipAddress = System.Net.IPAddress.Parse((message.Split('(')[1]).Split(')')[0].Trim()); } catch { }
                                        try { Form1.myForm.RemoteHost.intPortGetFile = Convert.ToInt32(message.Split(':')[2].Trim()); } catch { }
                                        Form1.myForm.RemoteHost.SetInfo();
                                    }
                                }

                                // Form1.myForm._richTextBoxEchoAdd(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " + message);

                                buffer = System.Text.Encoding.UTF8.GetBytes(encryptDecrypt.EncryptRijndael(message, salt));

                                //byte[] msg = System.Text.Encoding.UTF8.GetBytes(encryptDecrypt.EncryptRijndael("Hi!", salt));
                                await networkStream.WriteAsync(buffer, 0, buffer.Length);

                                buffer    = new byte[4096];
                                byteCount = await networkStream.ReadAsync(buffer, 0, buffer.Length);

                                message = encryptDecrypt.DecryptRijndael(Encoding.UTF8.GetString(buffer, 0, byteCount), salt);
                                //Write all info into log
                                //Form1.myForm._richTextBoxEchoAdd(DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": " + Form1.myForm.RemoteHost.UserName + ": " + message);

                                doAction         = new DoAction();
                                doAction.message = Form1.myForm.RemoteHost.UserName + " " + message;
                                doAction.CheckGotMessage();
                                if (doAction.ActionSelected == "NAME")
                                {
                                    buffer = System.Text.Encoding.UTF8.GetBytes(encryptDecrypt.EncryptRijndael(doAction.answer, salt));
                                    await networkStream.WriteAsync(buffer, 0, buffer.Length);
                                }
                                else if (doAction.ActionSelected == "TAKE")
                                {
                                    buffer = System.Text.Encoding.UTF8.GetBytes(encryptDecrypt.EncryptRijndael(doAction.answer, salt));
                                    // await networkStream.WriteAsync(buffer, 0, buffer.Length);
                                }
                                else if (doAction.ActionSelected == "UPDATESERVER")
                                {
                                    Random rnd           = new Random();
                                    string sActionFolder = rnd.Next().ToString();
                                    System.IO.DirectoryInfo UpdateFolderFullPath = new System.IO.DirectoryInfo(System.Windows.Forms.Application.StartupPath + "\\" + sActionFolder);

                                    try { UpdateFolderFullPath.Create(); } catch { }
                                    Form1.myForm.strFolderUpdates = UpdateFolderFullPath.ToString();
                                    try
                                    {
                                        using (Microsoft.Win32.RegistryKey EvUserKey = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(myRegKey))
                                        {
                                            EvUserKey.SetValue("UPDATESERVERFOLDER", encryptDecrypt.EncryptStringToBase64Text(Form1.myForm.strFolderUpdates, btsMess1, btsMess2), Microsoft.Win32.RegistryValueKind.String);
                                        }
                                    }
                                    catch { }

                                    string sPathCmd = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "myCltSvr.cmd");
                                    doAction.UpdateServerMakecmd(sPathCmd, sActionFolder);

                                    buffer = System.Text.Encoding.UTF8.GetBytes(encryptDecrypt.EncryptRijndael(Form1.myForm.LocalHost.UserName + ": Ready to get a file on the port: " + Form1.myForm.LocalHost.intPortGetFile, salt));
                                    await networkStream.WriteAsync(buffer, 0, buffer.Length);

                                    SendGetFile getFile = new SendGetFile();
                                    getFile.GetFile(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, sActionFolder), Form1.myForm.LocalHost.intPortGetFile);

                                    doAction.RunProcess(sPathCmd);
                                }
                                else if (doAction.ActionSelected == "GET") //Prepare to get file by Server
                                {
                                    SendGetFile getFile = new SendGetFile();
                                    buffer = System.Text.Encoding.UTF8.GetBytes(encryptDecrypt.EncryptRijndael(Form1.myForm.LocalHost.UserName + ": Ready to get a file on the port: " + Form1.myForm.LocalHost.intPortGetFile, salt));
                                    await networkStream.WriteAsync(buffer, 0, buffer.Length);  //Добавить cancelationtoken

                                    getFile.GetFile(Form1.myForm.strFolderGet, Form1.myForm.LocalHost.intPortGetFile);
                                }
                                else if (doAction.ActionSelected.Length > 0)
                                {
                                    cts = new System.Threading.CancellationTokenSource();
                                    bool messageIsCommand = false;
                                    foreach (string str in actionWord) //
                                    {
                                        if (doAction.ActionSelected == str)
                                        {
                                            messageIsCommand = true;
                                            break;
                                        }
                                    }
                                    if (messageIsCommand != true && Form1.myForm.controlled != "uncontrolcheck")
                                    {
                                        System.Threading.Tasks.Task.Run(() => MakeDelayForHide(10000), cts.Token); //отмена задачи если будет   cts.Cancel
                                    }

                                    buffer = System.Text.Encoding.UTF8.GetBytes(encryptDecrypt.EncryptRijndael(doAction.message, salt));
                                    await networkStream.WriteAsync(buffer, 0, buffer.Length);
                                }
                                else if (doAction.ActionSelected == "")
                                {
                                    buffer = System.Text.Encoding.UTF8.GetBytes(encryptDecrypt.EncryptRijndael(Form1.myForm.RemoteHost.UserName + ": said  -= " + message.ToUpper(), salt));
                                    await networkStream.WriteAsync(buffer, 0, buffer.Length);
                                }
                                else
                                {
                                    buffer = System.Text.Encoding.UTF8.GetBytes(encryptDecrypt.EncryptRijndael(Form1.myForm.RemoteHost.UserName + ": said nothing", salt));
                                    await networkStream.WriteAsync(buffer, 0, buffer.Length);
                                }
                                await networkStream.WriteAsync(buffer, 0, buffer.Length);
                            }
                            catch// (Exception expt)
                            {
                                //   Form1.myForm._AppendTextToFile(Form1.myForm.FileLog, DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": Listen().tcpClient.GetStream(): " + expt.ToString());
                            }
                        }
                    }
                }
            }
            catch (Exception expt)
            { Form1.myForm._AppendTextToFile(Form1.myForm.FileLog, DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString() + ": Listen(): " + expt.Message); }
            finally { tcpListener.Stop(); }
        }
        private void thread_start()
        {
            long nEventRecvCount = 0;

            appTrace.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0, "[thread_start] IN");
            appTrace.TraceEvent(System.Diagnostics.TraceEventType.Information, 0, "[thread_start] IN");

            Encoding enc = Encoding.UTF8;

            //System.Net.IPAddress ipAddsAny = System.Net.IPAddress.Any;
            //            System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(ipAddsAny, 55561);

            //  System.Net.IPAddress Ip = new System.Net.IPAddress(new byte[] { 192, 168, 0, 1 });
            // System.Net.IPAddress Ip = new System.Net.IPAddress(new byte[] { 192, 168, 77, 210 });
            //System.Net.IPAddress Ip = new System.Net.IPAddress(new byte[] { 192, 168, 77, 245 });

            System.Net.IPAddress Ip;
            string LocalIp = MainClass2.Setting.LocalIp;

            Utils.ToLog(String.Format("Запуск слушателя событий адрес {0}, порт {1}", LocalIp, MainClass2.Setting.EventLisenterPort));

            if (LocalIp.ToLower() == "localhost")
            {
                Ip = System.Net.IPAddress.Any;
            }
            else
            {
                try
                {
                    string s = LocalIp.Split("."[0])[0];
                    Ip = new System.Net.IPAddress(new byte[] { byte.Parse(LocalIp.Split("."[0])[0]), byte.Parse(LocalIp.Split("."[0])[1]), byte.Parse(LocalIp.Split("."[0])[2]), byte.Parse(LocalIp.Split("."[0])[3]) });
                }
                catch
                {
                    Ip = System.Net.IPAddress.Any;
                }
            }


            System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(Ip, MainClass2.Setting.EventLisenterPort);



            try
            {
                while (true)
                {
                    listener.Start();

                    Console.WriteLine("Start listern on Port{0}", MainClass2.Setting.EventLisenterPort);

                    System.Net.Sockets.TcpClient tcp;
                    tcp = listener.AcceptTcpClient();
                    Utils.ToLog(String.Format("Cлушатель событий запущен"));
                    Console.WriteLine("Client connected.");
                    appTrace.TraceInformation("Client connected.");

                    nEventRecvCount = 0;

                    System.Net.Sockets.NetworkStream ns = tcp.GetStream();

                    int    resSize;
                    string cmd       = "";
                    bool   CloseSock = false;
                    do
                    {
                        byte[] bytes = new byte[tcp.ReceiveBufferSize];
                        resSize = ns.Read(bytes, 0, tcp.ReceiveBufferSize);

                        if (resSize == 0)
                        {
                            Console.WriteLine("Client is disconnected.");
                            appTrace.TraceInformation("Client is disconnected.");
                            CloseSock = true;
                            break;
                        }

                        long s = 0;
                        long e = 0;
                        for (e = 0; e < resSize; e++)
                        {
                            if (bytes[e] == 0)
                            {
                                cmd += System.Text.Encoding.ASCII.GetString(bytes, (int)s, (int)(e - s));
                                Console.WriteLine("cmd : " + cmd);
                                // Here the event handling should be located.>>>>>>>>>>>>>>>
                                CheckRecvComand(cmd, nEventRecvCount);

                                // if one packet includes several events, then the next event
                                // also should be handled.
                                s = e + 1;

                                cmd = "";
                            }
                            else if (e == resSize - 1)
                            {
                                // If one event is separated to several packets, then they
                                // should be merged to one string.
                                cmd += System.Text.Encoding.ASCII.GetString(bytes, (int)s, (int)(e - s + 1));
                            }
                        }
                    } while (true);

                    if (CloseSock == false)
                    {
                        tcp.Close();
                        Console.WriteLine("Disconnected");
                        appTrace.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "Disconnected");
                        continue;
                    }

                    listener.Stop();
                    Console.WriteLine("Listener is closed.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                appTrace.TraceEvent(System.Diagnostics.TraceEventType.Critical, 0, ex.Message.ToString());
            }
        }
Esempio n. 31
0
            private int DequeueNextAvailablePort()
            {
                bool gotPort = false;
                int  currentPortFromqueue = 0;

                while (!gotPort)
                {
                    if (this._availablePortsList.Count > 0)
                    {
                        currentPortFromqueue = System.Convert.ToInt32(this._availablePortsList.GetByIndex(0));

                        lock (this._availablePortsList)
                        {
                            this._availablePortsList.RemoveAt(0);
                        }

                        System.Net.Sockets.TcpListener listener = null;
                        string host = System.Net.Dns.GetHostName();
                        System.Net.IPAddress local_IPAddress = CommunicationsLibrary.Utilities.CommunicationsUtilities.GetActiveIPAddress();
                        listener = new System.Net.Sockets.TcpListener(local_IPAddress, currentPortFromqueue);
                        try
                        {
                            listener.Start();
                            listener.Stop();
                            this._LastAssignedPortNumber = currentPortFromqueue;
                            listener = null;
                            gotPort  = true;
                        }
                        catch (System.Net.Sockets.SocketException ex)
                        {
                            switch (ex.ErrorCode)
                            {
                            case 10048:                                     //the port is opened by another process
                                try
                                {
                                    listener.Stop();
                                }
                                catch (Exception)
                                {
                                }
                                break;

                            case 10055:                                     //there is no more space to allocate another port in the system, no more resources available
                                string msg = "Error finding an open port : " + ex.Message;
                                throw (new Exception(msg));
                            }
                        }
                        catch (Exception)
                        {
                            try
                            {
                                listener.Stop();
                            }
                            catch (Exception)
                            {
                            }
                        }
                    }
                    else
                    {
                        this._LastAssignedPortNumber = CommunicationsUtilities.GetFreeTCPPortOnPortsRange(this._portsRangeLowerLimit, this._portsRangeUpperLimit);
                    }
                }

                return(this._LastAssignedPortNumber);
            }
Esempio n. 32
0
        static public string[] GetUrlList()
        {
            //ListenするIPアドレス
            string ipString = "localhost";

            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString);
            //Listenするポート番号
            int port = 8080;

            //TcpListenerオブジェクトを作成する
            System.Net.Sockets.TcpListener listener =
                new System.Net.Sockets.TcpListener(ipAdd, port);

            //Listenを開始する
            listener.Start();

            //接続要求があったら受け入れる
            System.Net.Sockets.TcpClient client = listener.AcceptTcpClient();

            //NetworkStreamを取得
            System.Net.Sockets.NetworkStream ns = client.GetStream();

            //読み取り、書き込みのタイムアウトを10秒にする
            //デフォルトはInfiniteで、タイムアウトしない
            //(.NET Framework 2.0以上が必要)
            ns.ReadTimeout  = 10000;
            ns.WriteTimeout = 10000;

            //クライアントから送られたデータを受信する
            bool          disconnected = false;
            List <string> urlList      = new List <string>();

            while (true)
            {
                string url = GetUrl(ns);
                if (url == null)
                {
                    disconnected = true;
                    break;
                }
                else
                {
                    urlList.Add(url);
                }
            }

            if (!disconnected)
            {
                //クライアントにデータを送信する
                //クライアントに送信する文字列を作成
                //文字列をByte型配列に変換
                byte[] sendBytes = enc.GetBytes("草生える" + '\n');
                //データを送信する
                ns.Write(sendBytes, 0, sendBytes.Length);
            }

            //閉じる
            ns.Close();
            client.Close();

            //リスナを閉じる
            listener.Stop();

            return(urlList.ToArray());
        }
Esempio n. 33
0
        /// <summary>
        /// エントリーポイント
        /// </summary>
        /// <param name="args">引数 席の総数を示す10進数整数 ポート番号</param>
        static int Main(string[] args)
        {
            string argErro = "引数は席数とポート番号の二つです";

            //引数確認
            if (args.Length != 2)
            {
                Console.WriteLine(argErro);
                return(1);
            }
            //グループ保存領域の初期化
            groups = new List <Group>();
            try
            {
                seats = new Group[int.Parse(args[0])];
            }
            catch
            {
                Console.WriteLine("席数は非負整数値です");
                return(1);
            }
            int listeningPortNomber;

            try
            {
                listeningPortNomber = int.Parse(args[1]);
                if (listeningPortNomber > 65535 | listeningPortNomber < 1024)
                {
                    Console.WriteLine("自由に使用可能なポート番号にしてください");
                    return(1);
                }
            }
            catch
            {
                Console.WriteLine(argErro);
                return(1);
            }
            //待ち受け準備と開始

            var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, listeningPortNomber);

            //外部でのプロセス監視用
            try
            {
                System.IO.StreamWriter sw = new System.IO.StreamWriter("pidgass.txt", false);
                sw.WriteLine(System.Diagnostics.Process.GetCurrentProcess().Id);
                sw.Close();
            }
            catch { }

            listener.Start();
            //クエリ受信開始
            do
            {
                System.Net.Sockets.TcpClient client = listener.AcceptTcpClient();
                var ns  = client.GetStream();
                var nsr = new System.IO.StreamReader(ns, System.Text.Encoding.UTF8);

                ns.ReadTimeout = ns.WriteTimeout = 10000;
                System.Text.Encoding enc = System.Text.Encoding.UTF8;
                bool disconnected        = false;
                //クエリ解釈して実行
                try
                {
                    string[] splitedQuery = nsr.ReadLine().Split(' ');
                    string   ans;
                    //入店
                    if (splitedQuery[0] == "OPEN"   | splitedQuery[0] == "SET")
                    {
                        ans = Open(splitedQuery);
                    }
                    //退店時処理
                    else if (splitedQuery[0] == "CLOSE" | splitedQuery[0] == "REMOVE")
                    {
                        ans = splitedQuery.Length != 2 ? "ERR INVALIED_COMMANDLENGTH" : Gremove_From_Seat(int.Parse(splitedQuery[1]));
                    }
                    //グループ情報取得
                    else if (splitedQuery[0] == "GET")
                    {
                        ans = Get();
                    }
                    //席の使用情報
                    else if (splitedQuery[0] == "SC")
                    {
                        ans = Seat_Chec();
                    }
                    //席の使用情報識別付き
                    else if (splitedQuery[0] == "SSC")
                    {
                        ans = SuperSeatCheck();
                    }
                    //グループの時間書き換え
                    else if (splitedQuery[0] == "TC")
                    {
                        ans = TimeChange(splitedQuery[1], splitedQuery[2]);
                    }
                    //席移動
                    else if (splitedQuery[0] == "CHS")
                    {
                        ans = SeatChange(int.Parse(splitedQuery[1]), splitedQuery[2].Split(','));
                    }
                    //未実装コマンド
                    else
                    {
                        ans = "ERRO THERE_IS_NOT_SUCH_A_COMMAND";
                    }
                    if (!disconnected)
                    {
                        ns.Write(enc.GetBytes(ans + '\n'), 0, enc.GetBytes(ans + '\n').Length);
                    }
                }
                catch { }
                try
                {
                    ns.Close();
                    client.Close();
                } catch { }
            } while (true);
        }
Esempio n. 34
0
        public OtpSelf(System.String node, System.String cookie, int port)
            : base(node, cookie)
        {
            System.Net.Sockets.TcpListener temp_tcplistener;
            //UPGRADE_NOTE: This code will be optimized in the future;
            temp_tcplistener = new System.Net.Sockets.TcpListener(System.Net.Dns.GetHostEntry("localhost").AddressList[0], port);
            temp_tcplistener.Start();
            sock = temp_tcplistener;

            if (port != 0)
                this._port = port;
            else
            {
                this._port = ((System.Net.IPEndPoint)sock.LocalEndpoint).Port;
            }

            this._pid = createPid();
        }
Esempio n. 35
0
        public virtual void Handshake() {
            if (serverSocket == null) {
                System.Net.IPHostEntry hostInfo = System.Net.Dns.GetHostEntry("localhost");
                System.Net.IPAddress ipAddress = hostInfo.AddressList[0];
                serverSocket = new TcpListener(ipAddress, port);
                socket = serverSocket.AcceptSocket();
                socket.NoDelay = true;

                System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                socket.Send(encoding.GetBytes("ANTLR " + DebugEventListenerConstants.ProtocolVersion + "\n"));
                socket.Send(encoding.GetBytes("grammar \"" + grammarFileName + "\n"));
                Ack();

                //serverSocket = new ServerSocket( port );
                //socket = serverSocket.accept();
                //socket.setTcpNoDelay( true );
                //OutputStream os = socket.getOutputStream();
                //OutputStreamWriter osw = new OutputStreamWriter( os, "UTF8" );
                //@out = new PrintWriter( new BufferedWriter( osw ) );
                //InputStream @is = socket.getInputStream();
                //InputStreamReader isr = new InputStreamReader( @is, "UTF8" );
                //@in = new BufferedReader( isr );
                //@out.println( "ANTLR " + DebugEventListenerConstants.PROTOCOL_VERSION );
                //@out.println( "grammar \"" + grammarFileName );
                //@out.flush();
                //ack();
            }
        }
Esempio n. 36
0
        public static void  Main(System.String[] args)
        {
            if (args.Length != 1)
            {
                System.Console.Out.WriteLine("\nUsage: java Lucene.Net.Store.LockVerifyServer port\n");
                System.Environment.Exit(1);
            }

            int port = System.Int32.Parse(args[0]);

            System.Net.Sockets.TcpListener temp_tcpListener;
            temp_tcpListener = new System.Net.Sockets.TcpListener(System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[0], port);
            temp_tcpListener.Server.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.ReuseAddress, 1);
            temp_tcpListener.Start();
            System.Net.Sockets.TcpListener s = temp_tcpListener;
            System.Console.Out.WriteLine("\nReady on port " + port + "...");

            int  lockedID  = 0;
            long startTime = (DateTime.UtcNow.Ticks / TimeSpan.TicksPerMillisecond);

            while (true)
            {
                System.Net.Sockets.TcpClient cs          = s.AcceptTcpClient();
                System.IO.Stream             out_Renamed = cs.GetStream();
                System.IO.Stream             in_Renamed  = cs.GetStream();

                int id      = in_Renamed.ReadByte();
                int command = in_Renamed.ReadByte();

                bool err = false;

                if (command == 1)
                {
                    // Locked
                    if (lockedID != 0)
                    {
                        err = true;
                        System.Console.Out.WriteLine(GetTime(startTime) + " ERROR: id " + id + " got lock, but " + lockedID + " already holds the lock");
                    }
                    lockedID = id;
                }
                else if (command == 0)
                {
                    if (lockedID != id)
                    {
                        err = true;
                        System.Console.Out.WriteLine(GetTime(startTime) + " ERROR: id " + id + " released the lock, but " + lockedID + " is the one holding the lock");
                    }
                    lockedID = 0;
                }
                else
                {
                    throw new System.SystemException("unrecognized command " + command);
                }

                System.Console.Out.Write(".");

                if (err)
                {
                    out_Renamed.WriteByte((System.Byte) 1);
                }
                else
                {
                    out_Renamed.WriteByte((System.Byte) 0);
                }

                out_Renamed.Close();
                in_Renamed.Close();
                cs.Close();
            }
        }
Esempio n. 37
0
        static void Main(string[] args)
        {
            //writes all available serial ports
            for (int i = 0; i < SerialPort.GetPortNames().Length; i++)
            {
                Console.WriteLine(SerialPort.GetPortNames()[i]);
            }

            //defualt for now will change to specific port for that robot.
            SerialPort serial = new SerialPort("COM4", 9600);

            serial.Parity = 0;
            //this creates a tcp socket on port 100 to localhost
            System.Net.IPAddress           ipAd = System.Net.IPAddress.Parse("127.0.0.1");
            System.Net.Sockets.TcpListener tcp  = new System.Net.Sockets.TcpListener(ipAd, 100);
            //this defines the client that is connected
            System.Net.Sockets.Socket client;

            //this runs the loop till end command
            bool run = true;


            //open the serial port
            try
            {
                serial.Open();
                //output the current state
                Console.WriteLine("Opened Comm port on port " + serial.PortName + " with baud rate " + serial.BaudRate);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }



            //open the tcp server
            tcp.Start();
            //output the current state
            Console.WriteLine("Opened tcp server on port 100 of " + ipAd.ToString());

            //create the client
            client = tcp.AcceptSocket();
            Console.WriteLine("Connected to client " + client.RemoteEndPoint);

            //run an inifinte loop of reading from tcp and writing to serial
            //and reading from serial to write to tcp
            while (run)
            {
                //the input buffer varaible
                if (client.ReceiveBufferSize > 0)
                {
                    byte[] inp = new byte[1];
                    //gets values from the stream and sends them out to serial
                    client.Receive(inp);
                    serial.Write(inp, 0, inp.Length);
                    Console.WriteLine("in from client: " + Convert.ToChar(inp[0]));
                }

                //gets value from serial and outputs it to tcp
                if (serial.BytesToRead > 0)
                {
                    //normal operation
                    byte[] outp = new byte[1];
                    serial.Read(outp, 0, outp.Length);
                    client.Send(outp);
                    Console.WriteLine("out to client: " + Convert.ToChar(outp[0]));
                }
            }
        }
 public void start(int port)
 {
     server  = new System.Net.Sockets.TcpListener(port);
     server.Start();
     server.BeginAcceptTcpClient(onClientConnect, server);
 }
Esempio n. 39
0
 public TcpListener(System.Net.Sockets.TcpListener tcpListener)
 {
     this.tcpListener = tcpListener;
 }
        /// <summary>
        /// 用于等待web访问,web访问线程的执行方
        /// </summary>
        void Web_WaitWebConnection()
        {
            System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, PORT);
            try
            {
                listener.Start();
            }
            catch (System.Net.Sockets.SocketException)
            {
                //已经被占用
                LogInToEvent.WriteError("端口" + PORT.ToString() + "已经被占用");
                System.Diagnostics.Process.GetCurrentProcess().Kill();
            }
            while (true)
            {
                var comein = listener.AcceptTcpClient();
                var dealing = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(Web_AfterConnectionGetReportAndSendToUser));
                dealing.Start(comein);

            }
        }
Esempio n. 41
0
 public TcpListener(IPEndPoint endpoint)
 {
     this.tcpListener = new System.Net.Sockets.TcpListener(endpoint);
 }
Esempio n. 42
0
        // 接続待ちスレッド用メソッド
        private void ListeningCallback()
        {
            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(this.ipString);

            //ホスト名からIPアドレスを取得する時は、次のようにする
            //string host = "localhost";
            //System.Net.IPAddress ipAdd =
            //    System.Net.Dns.GetHostEntry(host).AddressList[0];
            //.NET Framework 1.1以前では、以下のようにする
            //System.Net.IPAddress ipAdd =
            //    System.Net.Dns.Resolve(host).AddressList[0];

            //TcpListenerオブジェクトを作成する
            //            System.Net.Sockets.TcpListener listener =
            listener =
                new System.Net.Sockets.TcpListener(ipAdd, port);

            Console.WriteLine("Listenを開始しました({0}:{1})。",
                ((System.Net.IPEndPoint)listener.LocalEndpoint).Address,
                ((System.Net.IPEndPoint)listener.LocalEndpoint).Port);

            //try
            //{
                //Listenを開始する
                listener.Start();
            //}
            //catch
            //{
            //    listener.Stop();
            //    listener = null;
            //    return ;
            //}

            do
            {
                while (SLTAlive)
                {
                    if (listener.Pending() == true)
                    {
                        //接続要求があったら受け入れる
                        //                System.Net.Sockets.TcpClient client = listener.AcceptTcpClient();
                        client = listener.AcceptTcpClient();
                        if (client.Connected == true)
                        {
                            Console.WriteLine("クライアント({0}:{1})と接続しました。",
                                ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address,
                                ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port);
                            //NetworkStreamを取得
                            ns = client.GetStream();

                            //読み取り、書き込みのタイムアウトを10秒にする
                            //デフォルトはInfiniteで、タイムアウトしない
                            //(.NET Framework 2.0以上が必要)
                            ns.ReadTimeout = 10000;
                            ns.WriteTimeout = 10000;

                            //クライアントから送られたデータを受信する
                            System.Text.Encoding enc = System.Text.Encoding.UTF8;
                            bool disconnected = false;
                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            byte[] resBytes = new byte[256];
                            int resSize = 0;
                            do
                            {
                                //データの一部を受信する
                                resSize = ns.Read(resBytes, 0, resBytes.Length);
                                //Readが0を返した時はクライアントが切断したと判断
                                if (resSize == 0)
                                {
                                    disconnected = true;
                                    Console.WriteLine("クライアントが切断しました。");
                                    break;
                                }
                                //受信したデータを蓄積する
                                ms.Write(resBytes, 0, resSize);
                                //まだ読み取れるデータがあるか、データの最後が\nでない時は、
                                // 受信を続ける
                            } while (ns.DataAvailable || resBytes[resSize - 1] != '\n');
                            //受信したデータを文字列に変換
                            string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);
                            ms.Close();
                            //末尾の\nを削除
                            resMsg = resMsg.TrimEnd('\n');
                            Console.WriteLine(resMsg);

                            if (!disconnected)
                            {
                                //クライアントにデータを送信する
                                //クライアントに送信する文字列を作成
                                string sendMsg = resMsg.Length.ToString();
                                //文字列をByte型配列に変換
                                byte[] sendBytes = enc.GetBytes(sendMsg + '\n');
                                //データを送信する
                                ns.Write(sendBytes, 0, sendBytes.Length);
                                Console.WriteLine(sendMsg);
                            }
                        }
                    }
                }
                // 短時間だけ待機
                System.Threading.Thread.Sleep(100);
            } while (true);

            //閉じる
            //        ns.Close();
            //        client.Close();
            //        Console.WriteLine("クライアントとの接続を閉じました。");

            //リスナを閉じる
            //        listener.Stop();
            //        Console.WriteLine("Listenerを閉じました。");

            //        Console.ReadLine();
        }
Esempio n. 43
0
        public static int socketCom()
        {
            //ListenするIPの指定
            string IP_String = "0.0.0.0";

            System.Net.IPAddress IP_Address = System.Net.IPAddress.Parse(IP_String);

            //Listenするport番号
            int PORT = 5000;

            //TcpListenerオブジェクトの作成
            System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(IP_Address, PORT);

            //Listenを開始
            listener.Start();
//            Console.WriteLine("Listenを開始しました({0}:{1})", ((System.Net.IPEndPoint)listener.LocalEndpoint).Address,((System.Net.IPEndPoint)listener.LocalEndpoint).Port);

            //接続要求のチェック,受け入れ
            System.Net.Sockets.TcpClient client = listener.AcceptTcpClient();

/*            Console.WriteLine("クライアント({0}:{1})と接続しました。",
 *              ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address,
 *              ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port);
 */
            //NetworkStreamを取得
            System.Net.Sockets.NetworkStream ns = client.GetStream();

            //読み取り、書き込みのタイムアウトを10秒にする
            //デフォルトはInfiniteで、タイムアウトしない
            //(.NET Framework 2.0以上が必要)
            ns.ReadTimeout  = 10000;
            ns.WriteTimeout = 10000;

            //クライアントから送られたデータを受信する
            System.Text.Encoding enc = System.Text.Encoding.UTF8;
            bool disconnected        = false;

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            byte[] resBytes           = new byte[256];
            int    resSize            = 0;

            StreamReader sr     = new StreamReader(ns, enc);
            string       resMsg = String.Empty;

            string[] values = new string[3];
            do
            {
                resMsg = sr.ReadLine();
                if (resMsg == null)
                {
                    break;
                }
                Console.WriteLine(resMsg);

                values = resMsg.Split(' ');
                switch (values[0])
                {
                case "theta:":
                    thetaFromAndroid = double.Parse(values[1]);
                    break;

                case "dist:":
                    distFromAndroid = double.Parse(values[1]);
                    break;

                case "lean:":

                    break;

                default:
                    break;
                }
            } while (true);


            //受信したデータを文字列に変換
            resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);
            //末尾の\nを削除
            resMsg = resMsg.TrimEnd('\n');
            Console.WriteLine(resMsg);
            //閉じる
            ms.Close();
            ns.Close();
            client.Close();
//            Console.WriteLine("クライアントとの接続を閉じました。");

            //リスナを閉じる
            listener.Stop();
//            Console.WriteLine("Listenerを閉じました。");

            Console.ReadLine();
            return(1);   //規定文字が来たら,-1などを返すようにあとで変える
        }
Esempio n. 44
0
        static void Main(string[] args)
        {
            const int PORT = 8810;

            if (args.Length == 1)
            {
                uint msgId = 0;

                string dir = args[0];

                System.Net.Sockets.TcpListener server = null;
                try
                {
                    System.Net.IPEndPoint localAddress = new System.Net.IPEndPoint(0, PORT);
                    server = new System.Net.Sockets.TcpListener(localAddress);
                    server.Start();

                    System.Console.WriteLine("파일 다운로드 대기 중...");

                    while (true)
                    {
                        System.Net.Sockets.TcpClient client = server.AcceptTcpClient();
                        System.Console.WriteLine("{0} 연결", ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).ToString());

                        System.Net.Sockets.NetworkStream stream = client.GetStream();
                        FUP.Message reqMsg = FUP.MessageUtil.Receive(stream);

                        if (reqMsg.Header.MSGTYPE != FUP.CONSTANTS.REQ_FILE_SEND)
                        {
                            stream.Close();
                            client.Close();
                            continue;
                        }

                        FUP.BodyRequest reqBody = (FUP.BodyRequest)reqMsg.Body;

                        System.Console.WriteLine("파일 전송 요청이 왔습니다. 수락하시겠습니까? (yes/no)");
                        string answer = System.Console.ReadLine();

                        FUP.Message rspMsg = new FUP.Message();
                        rspMsg.Body = new FUP.BodyResponse()
                        {
                            MSGID    = reqMsg.Header.MSGID,
                            RESPONSE = FUP.CONSTANTS.ACCEPTED
                        };
                        rspMsg.Header = new FUP.Header()
                        {
                            MSGID      = msgId++,
                            MSGTYPE    = FUP.CONSTANTS.REP_FILE_SEND,
                            BODYLEN    = (uint)rspMsg.Body.GetSize(),
                            FRAGMENTED = FUP.CONSTANTS.NOT_FRAGMENTED,
                            LASTMSG    = FUP.CONSTANTS.LASTMSG,
                            SEQ        = 0
                        };

                        if (answer != "yes" && answer != "y")
                        {
                            rspMsg.Body = new FUP.BodyResponse()
                            {
                                MSGID    = reqMsg.Header.MSGID,
                                RESPONSE = FUP.CONSTANTS.DENIED
                            };
                            FUP.MessageUtil.Send(stream, rspMsg);
                            stream.Close();
                            client.Close();
                            continue;
                        }
                        else
                        {
                            FUP.MessageUtil.Send(stream, rspMsg);
                        }

                        System.Console.WriteLine("파일 전송을 시작합니다.");

                        if (System.IO.Directory.Exists(dir) == false)
                        {
                            System.IO.Directory.CreateDirectory(dir);
                        }

                        long   fileSize           = reqBody.FILESIZE;
                        string fileName           = System.Text.Encoding.Default.GetString(reqBody.FILENAME);
                        System.IO.FileStream file = new System.IO.FileStream(dir + "\\" + fileName, System.IO.FileMode.Create);

                        uint?  dataMsgId = null;
                        ushort prevSeq   = 0;
                        while ((reqMsg = FUP.MessageUtil.Receive(stream)) != null)
                        {
                            System.Console.Write("#");
                            if (reqMsg.Header.MSGTYPE != FUP.CONSTANTS.FILE_SEND_DATA)
                            {
                                break;
                            }

                            if (dataMsgId == null)
                            {
                                dataMsgId = reqMsg.Header.MSGID;
                            }
                            else
                            {
                                if (dataMsgId != reqMsg.Header.MSGID)
                                {
                                    break;
                                }
                            }

                            if (prevSeq++ != reqMsg.Header.SEQ)
                            {
                                System.Console.WriteLine("{0}, {1}", prevSeq, reqMsg.Header.SEQ);
                                break;
                            }

                            file.Write(reqMsg.Body.GetBytes(), 0, reqMsg.Body.GetSize());

                            if (reqMsg.Header.FRAGMENTED == FUP.CONSTANTS.NOT_FRAGMENTED)
                            {
                                break;
                            }
                            if (reqMsg.Header.LASTMSG == FUP.CONSTANTS.LASTMSG)
                            {
                                break;
                            }
                        }

                        long recvFileSize = file.Length;
                        file.Close();

                        System.Console.WriteLine();
                        System.Console.WriteLine("수신 파일 크기 : {0}byte", recvFileSize);

                        FUP.Message rstMsg = new FUP.Message();
                        rstMsg.Body = new FUP.BodyResult()
                        {
                            MSGID  = reqMsg.Header.MSGID,
                            RESULT = FUP.CONSTANTS.SUCCESS
                        };
                        rstMsg.Header = new FUP.Header()
                        {
                            MSGID      = msgId++,
                            MSGTYPE    = FUP.CONSTANTS.FILE_SEND_RES,
                            BODYLEN    = (uint)rstMsg.Body.GetSize(),
                            FRAGMENTED = FUP.CONSTANTS.NOT_FRAGMENTED,
                            LASTMSG    = FUP.CONSTANTS.LASTMSG,
                            SEQ        = 0
                        };

                        if (fileSize == recvFileSize)
                        {
                            FUP.MessageUtil.Send(stream, rstMsg);
                        }
                        else
                        {
                            rstMsg.Body = new FUP.BodyResult()
                            {
                                MSGID  = reqMsg.Header.MSGID,
                                RESULT = FUP.CONSTANTS.FAIL
                            };

                            FUP.MessageUtil.Send(stream, rstMsg);
                        }
                        System.Console.WriteLine("파일 전송을 마쳤습니다.");

                        stream.Close();
                        client.Close();
                    }
                }
                catch (System.Net.Sockets.SocketException e)
                {
                    System.Console.WriteLine(e);
                }
                finally
                {
                    server.Stop();
                }
            }
            else if (args.Length == 2)
            {
                const int CHUNK_SIZE = 4096;

                string serverIp = args[0];
                string filepath = args[1];

                try
                {
                    System.Net.IPEndPoint clientAddress = new System.Net.IPEndPoint(0, 0);
                    System.Net.IPEndPoint serverAddress = new System.Net.IPEndPoint(System.Net.IPAddress.Parse(serverIp), PORT);
                    System.IO.FileInfo    fileinfo      = new System.IO.FileInfo(filepath);

                    System.Console.WriteLine("클라이언트: {0}, 서버: {0}", clientAddress.ToString(), serverAddress.ToString());

                    uint msgId = 0;

                    FUP.Message reqMsg = new FUP.Message();
                    reqMsg.Body = new FUP.BodyRequest()
                    {
                        FILESIZE = fileinfo.Length,
                        FILENAME = System.Text.Encoding.Default.GetBytes(fileinfo.Name)
                    };
                    reqMsg.Header = new FUP.Header()
                    {
                        MSGID      = msgId++,
                        MSGTYPE    = FUP.CONSTANTS.REQ_FILE_SEND,
                        BODYLEN    = (uint)reqMsg.Body.GetSize(),
                        FRAGMENTED = FUP.CONSTANTS.NOT_FRAGMENTED,
                        LASTMSG    = FUP.CONSTANTS.LASTMSG,
                        SEQ        = 0
                    };

                    System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(clientAddress);
                    client.Connect(serverAddress);

                    System.Net.Sockets.NetworkStream stream = client.GetStream();

                    FUP.MessageUtil.Send(stream, reqMsg);

                    FUP.Message rspMsg = FUP.MessageUtil.Receive(stream);

                    if (rspMsg.Header.MSGTYPE != FUP.CONSTANTS.REP_FILE_SEND)
                    {
                        System.Console.WriteLine("정상적인 서버 응답이 아닙니다. {0}", rspMsg.Header.MSGTYPE);
                        return;
                    }

                    if (((FUP.BodyResponse)rspMsg.Body).RESPONSE == FUP.CONSTANTS.DENIED)
                    {
                        System.Console.WriteLine("서버에서 파일 전송을 거부했습니다.");
                        return;
                    }

                    using (System.IO.Stream fileStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open))
                    {
                        byte[] rbytes = new byte[CHUNK_SIZE];

                        long readValue = System.BitConverter.ToInt64(rbytes, 0);

                        int    totalRead  = 0;
                        ushort msgSeq     = 0;
                        byte   fragmented = (fileStream.Length < CHUNK_SIZE) ? FUP.CONSTANTS.NOT_FRAGMENTED : FUP.CONSTANTS.FRAGMENTED;
                        while (totalRead < fileStream.Length)
                        {
                            int read = fileStream.Read(rbytes, 0, CHUNK_SIZE);
                            totalRead += read;
                            FUP.Message fileMsg = new FUP.Message();

                            byte[] sendBytes = new byte[read];
                            System.Array.Copy(rbytes, 0, sendBytes, 0, read);

                            fileMsg.Body   = new FUP.BodyData(sendBytes);
                            fileMsg.Header = new FUP.Header()
                            {
                                MSGID      = msgId,
                                MSGTYPE    = FUP.CONSTANTS.FILE_SEND_DATA,
                                BODYLEN    = (uint)fileMsg.Body.GetSize(),
                                FRAGMENTED = fragmented,
                                LASTMSG    = (totalRead < fileStream.Length) ? FUP.CONSTANTS.NOT_LASTMSG : FUP.CONSTANTS.LASTMSG,
                                SEQ        = msgSeq++
                            };

                            System.Console.Write("#");

                            FUP.MessageUtil.Send(stream, fileMsg);
                        }

                        System.Console.WriteLine();
                        FUP.Message    rstMsg = FUP.MessageUtil.Receive(stream);
                        FUP.BodyResult result = (FUP.BodyResult)rstMsg.Body;
                        System.Console.WriteLine("파일 전송을 마쳤습니다.");
                    }

                    stream.Close();
                    client.Close();
                }
                catch (System.Net.Sockets.SocketException e)
                {
                    System.Console.WriteLine(e);
                }
            }
            else
            {
                System.Console.WriteLine("파일 받는 법:\t{0} \"다운로드 경로\"", System.Diagnostics.Process.GetCurrentProcess().ProcessName);
                System.Console.WriteLine("파일 보내는 법:\t{0} \"보낼 IP\" \"업로드할 파일\"", System.Diagnostics.Process.GetCurrentProcess().ProcessName);
            }
            return;
        }
Esempio n. 45
0
        static void Main(string[] args)
        {
            String[] src = File.ReadAllLines(@"C:\Users\ymine\skkdic\SKK-JISYO.L", Encoding.GetEncoding("EUC-JP"));
            if (src == null)
            {
                System.Environment.Exit(0);
            }
            List <String> dic = new List <string>(src);

            dic.Sort();
            List <String> midasi = new List <string>();

            foreach (String item in dic)
            {
                midasi.Add(item.Split(' ')[0]);
            }

            //ListenするIPアドレス
            string ipString = "127.0.0.1";

            System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse(ipString);

            //ホスト名からIPアドレスを取得する時は、次のようにする
            //string host = "localhost";
            //System.Net.IPAddress ipAdd =
            //    System.Net.Dns.GetHostEntry(host).AddressList[0];
            //.NET Framework 1.1以前では、以下のようにする
            //System.Net.IPAddress ipAdd =
            //    System.Net.Dns.Resolve(host).AddressList[0];

            //Listenするポート番号
            int port = 2001;

            //TcpListenerオブジェクトを作成する
            System.Net.Sockets.TcpListener listener =
                new System.Net.Sockets.TcpListener(ipAdd, port);

            //Listenを開始する
            listener.Start();
            Console.WriteLine("Listenを開始しました({0}:{1})。",
                              ((System.Net.IPEndPoint)listener.LocalEndpoint).Address,
                              ((System.Net.IPEndPoint)listener.LocalEndpoint).Port);

            //接続要求があったら受け入れる
            System.Net.Sockets.TcpClient client = listener.AcceptTcpClient();
            Console.WriteLine("クライアント({0}:{1})と接続しました。",
                              ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Address,
                              ((System.Net.IPEndPoint)client.Client.RemoteEndPoint).Port);

            //NetworkStreamを取得
            System.Net.Sockets.NetworkStream ns = client.GetStream();

            //読み取り、書き込みのタイムアウトを10秒にする
            //デフォルトはInfiniteで、タイムアウトしない
            //(.NET Framework 2.0以上が必要)
            // ns.ReadTimeout = 10000;
            // ns.WriteTimeout = 10000;

            //クライアントから送られたデータを受信する
            System.Text.Encoding enc = System.Text.Encoding.UTF8;
            bool disconnected        = false;

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            byte[] resBytes           = new byte[256];
            int    resSize            = 0;

            /**
             * while ((resSize = ns.Read(resBytes, 0, resBytes.Length)) != 0)
             * {
             *  ms.Write(resBytes, 0, resSize);
             * }
             * */
            do
            {
                //データの一部を受信する
                resSize = ns.Read(resBytes, 0, resBytes.Length);
                //Readが0を返した時はクライアントが切断したと判断
                if (resSize == 0)
                {
                    disconnected = true;
                    Console.WriteLine("クライアントが切断しました。");
                    break;
                }
                //受信したデータを蓄積する
                ms.Write(resBytes, 0, resSize);
                //まだ読み取れるデータがあるか、データの最後が\nでない時は、
                // 受信を続ける
            } while (ns.DataAvailable || resBytes[resSize - 1] != '\n');
            //受信したデータを文字列に変換
            string resMsg = enc.GetString(ms.GetBuffer(), 0, (int)ms.Length);

            ms.Close();
            //末尾の\nを削除
            resMsg = resMsg.TrimEnd('\n');
            // resMsg = resMsg.TrimEnd('\r');
            Console.WriteLine(resMsg);
            int    index   = midasi.BinarySearch(resMsg);
            String sendMsg = String.Empty;

            if (index > -1)
            {
                sendMsg = dic[index].Split(' ')[1];
            }
            else
            {
                sendMsg = "Not found...";
            }
            //クライアントにデータを送信する
            //クライアントに送信する文字列を作成
            //文字列をByte型配列に変換
            byte[] sendBytes = enc.GetBytes(sendMsg + '\n');
            //データを送信する
            ns.Write(sendBytes, 0, sendBytes.Length);
            Console.WriteLine(sendMsg);

            //閉じる
            ns.Close();
            client.Close();
            Console.WriteLine("クライアントとの接続を閉じました。");

            //リスナを閉じる
            listener.Stop();
            Console.WriteLine("Listenerを閉じました。");

            Console.ReadLine();
        }
Esempio n. 46
0
		public virtual void Handshake()
		{
			if (serverSocket == null)
			{
				serverSocket = new TcpListener(port);
				serverSocket.Start();
				socket = serverSocket.AcceptTcpClient();
				socket.NoDelay = true;

				reader = new StreamReader(socket.GetStream(), Encoding.UTF8);
				writer = new StreamWriter(socket.GetStream(), Encoding.UTF8);

				writer.WriteLine("ANTLR " + Constants.DEBUG_PROTOCOL_VERSION);
				writer.WriteLine("grammar \"" + grammarFileName);
				writer.Flush();
				Ack();
			}
		}
Esempio n. 47
0
        public static void doLoad()
        {
#if DEBUG
#else
            try
            {
#endif
            Model.SystemLog.addEntry("---------------");
            Model.SystemLog.addEntry("");
            Model.SystemLog.addEntry("Startup at " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString());


            speedLimiter = new Model.GlobalSpeedLimiter();
            string username = settings.getString("Username", Environment.MachineName);
            settings.setString("Username", username);


            try
            {
                udp2 = new System.Net.Sockets.UdpClient(Dimension.Model.NetConstants.controlPort);
            }
            catch
            {
            }

            Model.SystemLog.addEntry("Setting up NAT...");
            bootstrap = new Model.Bootstrap();
            try
            {
                bootstrap.launch().Wait();
            }
            catch (System.TypeLoadException)
            {
                System.Windows.Forms.MessageBox.Show("Error! It looks like you don't have .NET 4.5 x86 installed.");
                System.Windows.Forms.Application.Exit();
                return;
            }
            listener = bootstrap.listener;
            udp      = bootstrap.unreliableClient;
            System.Threading.Thread t = new System.Threading.Thread(acceptLoop);
            t.IsBackground = true;
            t.Name         = "UDT Accept Loop";
            t.Start();
            fileListDatabase = new Model.FileListDatabase();

            Model.SystemLog.addEntry("Creating File List Manager...");
            fileList = new Model.FileList();


            Model.SystemLog.addEntry("Creating a serializer...");
            serializer = new Model.Serializer();

            Model.SystemLog.addEntry("Creating the client core...");
            theCore = new Model.Core();

            Model.SystemLog.addEntry("Starting Kademlia launching...");
            kademlia = new Model.Kademlia();
            if (!isMono)
            {
                t = new System.Threading.Thread(delegate()
                {
                    kademlia.initialize();
                });
                t.IsBackground = true;
                t.Name         = "Kademlia Init Thread";
                t.Start();
            }
            Model.SystemLog.addEntry("Starting a file list update...");
            fileList.startUpdate(false);

            Model.SystemLog.addEntry("Saving settings...");
            App.settings.save();

            Model.SystemLog.addEntry("Done loading!");
            doneLoading = true;
#if DEBUG
#else
        }

        catch (Exception e)
        {
            Model.SystemLog.addEntry("Exception!");
            Model.SystemLog.addEntry(e.Message);
            Model.SystemLog.addEntry(e.StackTrace);
        }
#endif
        }