当前位置: 首页>>代码示例>>C#>>正文


C# TcpClient类代码示例

本文整理汇总了C#中TcpClient的典型用法代码示例。如果您正苦于以下问题:C# TcpClient类的具体用法?C# TcpClient怎么用?C# TcpClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


TcpClient类属于命名空间,在下文中一共展示了TcpClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: HandleInvoke

    public void HandleInvoke(TcpClient client, string values) {
        SplitData data = values.GetFirst();

        switch (data.CommandType) {
            case "StartGame":
                Debug.Log("TODO: Add game start");
                break;
            case "CreateUnit":
                CreateUnit(data.Values);
                break;
            case "SplitUnit":
                SplitUnit(data.Values);
                break;
            case "MoveToEmpty":
                Move(_invoke.MoveToEmpty, data.Values);
                break;
            case "MoveToMerge":
                Move(_invoke.MoveToMerge, data.Values);
                break;
            case "MoveToAttack":
                Move(_invoke.MoveToAttack, data.Values);
                break;
            case "CashChanged":
                CashChanged(data.Values);
                break;
            default:
                Debug.LogError("Invalid message send to Invokable\n" + values);
                break;
        }
    }
开发者ID:BornToGrill,项目名称:Project-Frequency,代码行数:30,代码来源:Invokable.cs

示例2: btnConnect_Click

        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                client = new TcpClient("127.0.0.1", 2000);
                ns = client.GetStream();
                sr = new StreamReader(ns);
                sw = new StreamWriter(ns);

                String response = sr.ReadLine();

                DelegateResponse dr = writeResponse;
                dr(response);
                // rawdata = [email protected]@[email protected]
                string rawData = imei.ToString();
                rawData += "@" + randomCoordinates();

                rawData +="@"+ ConvertToTimestamp(DateTime.Now).ToString();
                

                 String data = stringToHexa(rawData);

                sw.WriteLine(data);
                sw.Flush();

            }
            catch (Exception err)
            {
                Console.WriteLine(err.ToString());
                //  throw;
            }
        }
开发者ID:Maldercito,项目名称:geoworks,代码行数:32,代码来源:1456391338$form1.cs

示例3: LEDSingleSwitch

    void LEDSingleSwitch()
    {
        //IPアドレスとポート番号を指定
        //string型とint型なのが不思議
        //勿論送信先のIPアドレスとポート番号です
        string ipAddress = "172.20.11.68";
        int port = 14649;

        //IPアドレスとポート番号を渡してサーバ側へ接続
        TcpClient client = new TcpClient(ipAddress, port);

        //表示するのは「Hello! C#」
        //これを送信用にbyte型へ直します

        string str = "SET_SINGLE " +number+ " " +single+ "," +single+ "," +single+ "," +single+ ",\nUPDATE\nUPDATE\n";
        byte[] tmp = Encoding.UTF8.GetBytes(str);

        //NWのデータを扱うストリームを作成
        NetworkStream stream = client.GetStream();

        //送信
        //引数は(データ , データ書き込み開始位置 , 書き込むバイト数)
        //だそうです
        stream.Write(tmp, 0, tmp.Length);

        //サーバとの接続を終了
        client.Close();
    }
开发者ID:kentx422,项目名称:Unity_BackUp,代码行数:28,代码来源:easyLux.cs

示例4: AddPlayer

        public void AddPlayer(TcpClient client)
        {
            //Caso já se tenha 02 jogadores, não pode mais entrar no servidor.
            if (ready)
                DisconnectPlayer(client);

            //Identificador do cliente
            int id = NextID();
            Console.WriteLine("Novo cliente entrou: " + id);

            //Cria Thread para cuidar do cliente.
            players[id] = new ClientProcessor(this, id, client);
            Thread thread = new Thread(players[id].Run);
            thread.Start();

            if (id + 1 >= MAX_PLAYERS)
            {
                ready = true;
                //Cria o contorno da parede e envia aos clientes.
                matrizJogo =  wall.CreateWallPhase01(matrizJogo);
                wall.SendToCLient(players, matrizJogo);

                // Cria a 1ª posicao da comida e envia ao cliente.
                matrizJogo = food.NewPosition(matrizJogo);
                food.SendToClient(matrizJogo, players);
            }
        }
开发者ID:nando29,项目名称:snake-multiplayer-csharp,代码行数:27,代码来源:GameState.cs

示例5: Main

	static void Main (string [] args)
	{
		int i = 0;

		while (args [i].StartsWith ("-")){
			if (args [i] == "-debug")
				debug = true;
			if (args [i] == "-headers")
				headers = true;
			if (args [i] == "-header")
				header = args [++i];
			i++;
		}
		
		c = new TcpClient (args [i], Int32.Parse (args [i+1]));
		c.ReceiveTimeout = 1000;
		ns = c.GetStream ();
		
		sw = new StreamWriter (ns);
		sr = new StreamReader (ns);

		string host = args [i];
		if (args [i+1] != "80")
			host += ":" + args [i+1];
		send (String.Format ("GET {0} HTTP/1.1\r\nHost: {1}\r\n\r\n", args [i+2], host));

		MemoryStream ms = new MemoryStream ();
		
		try {
			byte [] buf = new byte [1024];
			int n;
			
			while ((n = ns.Read (buf, 0, 1024)) != 0){
				ms.Write (buf, 0, n);
			}
		} catch {}

		ms.Position = 0;
		sr = new StreamReader (ms);

		string s;
		
		while ((s = sr.ReadLine ()) != null){
			if (s == ""){
				if (headers)
					return;
				
				string x = sr.ReadToEnd ();
				Console.Write (x);
				break;
			}  else {
				if (debug || headers)
					Console.WriteLine (s);
				if (header != null && s.StartsWith (header)){
					Console.WriteLine (s);
					return;
				}
			}
		}
	}
开发者ID:nobled,项目名称:mono,代码行数:60,代码来源:rtest.cs

示例6: ThreadListener

    private void ThreadListener()
    {
        client = new TcpClient();
        try
        {
            client.Connect(host, port);
            ns = client.GetStream();

            write("READY");

            running = true;
            while (running)
            {
                threadUpdate();
            }
        }
        catch (SocketException e)
        {
            Debug.LogException(e, this);
            if (!running)
            {
                //tenta conectar novamente
                ThreadListener();
            }
            else
            {
                GameController.gameState = GameController.GameState.EXIT;
            }
        }
    }
开发者ID:valdenio,项目名称:BatalhaDoUniverso,代码行数:30,代码来源:GameSocketConnectionThread.cs

示例7: Execute

        public void Execute()
        {
            //   throw new Exception("aasd");

            var tcpClient = new TcpClient(ServerLocation, ServerPort);
            var skynet = new SkynetClient("Client", tcpClient, null);
            skynet.Connect(true, false, TimeSpan.FromSeconds(60));
            try
            {
                var assembly = Assembly.LoadFrom(File);

                assembly.EntryPoint.Invoke(null, new object[] { new string[] { "args" } });
                new ManualResetEvent(false).WaitOne(1000);
            }
            catch (Exception ex)
            {
                log.Error("Failed to start process", ex);

                Environment.Exit(0);
            }

            //  runner.Start("");

            Environment.Exit(1);
        }
开发者ID:Elders,项目名称:Skynet,代码行数:25,代码来源:SimpleClient.cs

示例8: Main

	public static void Main() {
		
		try {
			TcpClient tcpclnt = new TcpClient();
			Console.WriteLine("Connecting.....");
			
			tcpclnt.Connect("172.21.5.99",8001); // use the ipaddress as in the server program
			
			Console.WriteLine("Connected");
			Console.Write("Enter the string to be transmitted : ");
			
			String str=Console.ReadLine();
			Stream stm = tcpclnt.GetStream();
						
			ASCIIEncoding asen= new ASCIIEncoding();
			byte[] ba=asen.GetBytes(str);
			Console.WriteLine("Transmitting.....");
			
			stm.Write(ba,0,ba.Length);
			
			byte[] bb=new byte[100];
			int k=stm.Read(bb,0,100);
			
			for (int i=0;i<k;i++)
				Console.Write(Convert.ToChar(bb[i]));
			
			tcpclnt.Close();
		}
		
		catch (Exception e) {
			Console.WriteLine("Error..... " + e.StackTrace);
		}
	}
开发者ID:ppatoria,项目名称:SoftwareDevelopment,代码行数:33,代码来源:clnt.cs

示例9: connect

 public void connect()
 {
     if(tcpClient == null) {
         tcpClient = new TcpClient(host, port);
         Debug.Log("Connected to socket " + host + ":" + port);
     }
 }
开发者ID:Noah-Huppert,项目名称:Inertial-Motion-Capture,代码行数:7,代码来源:SocketClient.cs

示例10: Connect

    public void Connect()
    {
        while(true){
            try {
                if(isConnected){
                    if(!IsConnected()){
                        Close();
                    }
                }
                else{
                    Log.AddToLog("Trying to Connect...");
                    TcpClient client = new TcpClient(host, port);
                    Log.AddToLog("Connected");
                    socket = client.Client;

                    writeThread = new Thread(Send_Threaded);
                    writeThread.Start();

                    readThread = new Thread(Read_Threaded);
                    readThread.Start();

                    isConnected = true;
                }

                mainWaitInLine.WaitOne(2000);
            }
            catch (Exception e) {
                Log.AddToDebug("setupSocket: " + e.ToString());
                lastError = e.ToString();
                isConnected = false;
            }
        }
    }
开发者ID:mariojgpinto,项目名称:PCMobileCOM,代码行数:33,代码来源:SocketClient.cs

示例11: ConnectionHandler

 public ConnectionHandler(Client mainForm)
 {
     this.mainForm = mainForm;
     ServerSocket = new TcpClient();
     messageHandler = new MessageHandler();
     PacketManager.DefineOpcodeHandlers();
 }
开发者ID:thebillkidy,项目名称:INF202A_DotNetDeel2,代码行数:7,代码来源:ConnectionHandler.cs

示例12: Initialize

    public override void Initialize(IEventSource eventSource)
    {      
        try
        {
            this.InitializeParameters();
 
            this.SubscribeToEvents(eventSource);
 
            log.Info("Initialize MS Build Logger!");
 
            string ipStr = GetParameterValue("ip");
            IPAddress ipServer = IPAddress.Parse(ipStr);
            int port = int.Parse(GetParameterValue("port"));
            log.InfoFormat("MS Build Logger port to write {0}", port);
 
            clientSocketWriter = new System.Net.Sockets.TcpClient();
            clientSocketWriter.Connect(ipServer, port);
            networkStream = clientSocketWriter.GetStream();
            Thread.Sleep(1000);
        }
        catch(Exception ex)
        {
            log.Error("Exception in MS Build logger", ex);
        }    
    }  
开发者ID:kennedykinyanjui,项目名称:Projects,代码行数:25,代码来源:TcpIpLogger.cs

示例13: sendPacket

 public string sendPacket(string packet)
 {
     try
     {
         TcpClient client = new TcpClient(ipAddress, port);
         Byte[] data = System.Text.Encoding.ASCII.GetBytes(packet);
         NetworkStream stream = client.GetStream();
         stream.Write(data, 0, data.Length);
         data = new Byte[256];
         String responseData = String.Empty;
         Int32 bytes = stream.Read(data, 0, data.Length);
         responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
         stream.Close();
         client.Close();
         return responseData;
     }
     catch (ArgumentNullException e)
     {
         return(e.ToString());
     }
     catch (SocketException e)
     {
         return (e.ToString());
     }
 }
开发者ID:cosmicpeanut,项目名称:ChatApplication,代码行数:25,代码来源:Packet.cs

示例14: fnConnectResult

 public string fnConnectResult(string sNetIP, int iPORT_NUM,string sUserName)
 {
     try
     {
         // GET LOCAL IP ADDRESS
         /*
         string strHostName = "";
         strHostName = System.Net.Dns.GetHostName();
         IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
         IPAddress[] addr = ipEntry.AddressList;
         Debug.Log( addr[addr.Length-1].ToString() );
         sNetIP = addr[addr.Length-1].ToString();
         */
         sNetIP = "localhost";
         // SET UP NEW TCP CLIENT AND CONNECT
         client = new TcpClient(sNetIP, PORT_NUM);
         client.GetStream().BeginRead(readBuffer, 0, READ_BUFFER_SIZE, new AsyncCallback(DoRead), null);
         Debug.Log("Connection Succeeded");
         //SendData("test");
         return "Connection Succeeded";
     }
     catch(Exception ex)
     {
         return "Server is not active.  Please start server and try again.      " + ex.ToString();
     }
 }
开发者ID:SLIPD,项目名称:PC,代码行数:26,代码来源:NetworkUDP.cs

示例15: Connect

    public static bool Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
    {
        TimeoutObject.Reset();
        socketexception = null;

        string serverip = Convert.ToString(remoteEndPoint.Address);
        int serverport = remoteEndPoint.Port;
        TcpClient tcpclient = new TcpClient();

        tcpclient.BeginConnect(serverip, serverport, new AsyncCallback(CallBackMethod), tcpclient);

        if (TimeoutObject.WaitOne(timeoutMSec, false))
        {
            if (IsConnectionSuccessful)
            {
                tcpclient.Close();
                return true;
            }
            else
            {
                tcpclient.Close();
                return false;
            }
        }
        else
        {
            tcpclient.Close();
            return false;
        }
    }
开发者ID:UkiMiawz,项目名称:data-communication,代码行数:30,代码来源:NetworkHelper.cs


注:本文中的TcpClient类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。