Csharp/CSharp Tutorial/Network/TcpClient

Материал из .Net Framework эксперт
Версия от 12:20, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Create BinaryWriter and BinaryReader from TcpClient

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
class MainClass
{
    public static void Main() 
    {
        TcpClient client = new TcpClient();
        try
        {
            Console.WriteLine("Attempting to connect to the server ","on port 8000.");
            client.Connect(IPAddress.Parse("127.0.0.1"), 8000);
            Console.WriteLine("Connection established.");
            NetworkStream stream = client.GetStream();
            using (BinaryWriter w = new BinaryWriter(stream))
            {
            }
            using (BinaryReader r = new BinaryReader(stream))
            {
            }
        }
        catch (Exception err)
        {
            Console.WriteLine(err.ToString());
        }
        finally
        {
            client.Close();
            Console.WriteLine("Port closed.");
        }
    }
}

Create NetworkStream from TcpClient

using System;
using System.IO;
using System.Net.Sockets ;
class MainClass
{
  public static void Main() 
  {
    TcpClient newSocket = new TcpClient("localhost", 50001);
    NetworkStream ns = newSocket.GetStream();
    byte[] buf = new byte[100];
    ns.Read(buf, 0, 100);
    char[] buf2 = new char[100];
    for(int i=0;i<100;i++)
      buf2[i]=(char)buf[i];
    Console.WriteLine(buf2);
    ns.Close();
    newSocket.Close();
  }
}

Creating Socket Connections

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MainClass 
{
    [STAThread]
    static void Main(string[] args)
    {
        TcpClient MyClient = new TcpClient();
        MyClient.Connect("localhost", 10000);
        NetworkStream MyNetStream = MyClient.GetStream();
            
        if(MyNetStream.CanWrite && MyNetStream.CanRead)
        {
            Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there");
            MyNetStream.Write(sendBytes, 0, sendBytes.Length);
      
            byte[] bytes = new byte[MyClient.ReceiveBufferSize];
            MyNetStream.Read(bytes, 0, (int) MyClient.ReceiveBufferSize);
    
            string returndata = Encoding.ASCII.GetString(bytes);
            Console.WriteLine("This is what the host returned to you: " + returndata);
        }else if (!MyNetStream.CanRead) {
            Console.WriteLine("You can not write data to this stream");
            MyClient.Close();
        }else if (!MyNetStream.CanWrite)
        {             
            Console.WriteLine("You can not read data from this stream");
            MyClient.Close();
        }   
    }   
}

Network Client and StreamReader

using System;
using System.Net.Sockets;
using System.Threading;
using System.Text;
public class MainClass
{
    public static void Main()
    {
        int BufferSize = 256;
        TcpClient tcpSocket = new TcpClient("127.0.0.1", 65000);
        NetworkStream  streamToServer = tcpSocket.GetStream();
        System.IO.StreamWriter writer = new System.IO.StreamWriter(streamToServer);
        writer.Write("message");
        writer.Flush();
        bool fQuit = false;
        while (!fQuit)
        {
            char[] buffer = new char[BufferSize];
            System.IO.StreamReader reader = new System.IO.StreamReader(streamToServer);
            int bytesRead = reader.Read(buffer, 0, BufferSize);
            if (bytesRead == 0)
                fQuit = true;
            else {
                string theString = new String(buffer);
                Console.WriteLine(theString);
            }
        }
        streamToServer.Close();
    }
}

Network Client with TcpClient and NetworkStream

using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;

    public class AsynchNetworkClient
    {
        public static Main()
        {
            
            TcpClient tcpSocket = new TcpClient("127.0.0.1", 65000);
            NetworkStream streamToServer = tcpSocket.GetStream();
            
            System.IO.StreamWriter writer =new System.IO.StreamWriter(streamToServer);
            writer.WriteLine("Hello Programming C#");
            writer.Flush();
            System.IO.StreamReader reader =new System.IO.StreamReader(streamToServer);
            string strResponse = reader.ReadLine();
            Console.WriteLine("Received: {0}", strResponse);
            streamToServer.Close();
        }
    }

Use a NetworkStream to read from a server

using System;
using System.IO;
using System.Net.Sockets ;
class MainClass
{
  public static void Main() 
  {
    TcpClient newSocket = new TcpClient("localhost", 50001);
    NetworkStream ns = newSocket.GetStream();
    byte[] buf = new byte[100];
    ns.Read(buf, 0, 100);
    char[] buf2 = new char[100];
    for(int i=0;i<100;i++)
      buf2[i]=(char)buf[i];
    Console.WriteLine(buf2);
    ns.Close();
    newSocket.Close();
  }
}

use TcpClient to connect to a server

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
class MainClass
{
    public static void Main() 
    {
        TcpClient client = new TcpClient();
        try
        {
            Console.WriteLine("Attempting to connect to the server ","on port 8000.");
            client.Connect(IPAddress.Parse("127.0.0.1"), 8000);
            Console.WriteLine("Connection established.");
            NetworkStream stream = client.GetStream();
            using (BinaryWriter w = new BinaryWriter(stream))
            {
            }
            using (BinaryReader r = new BinaryReader(stream))
            {
            }
        }
        catch (Exception err)
        {
            Console.WriteLine(err.ToString());
        }
        finally
        {
            client.Close();
            Console.WriteLine("Port closed.");
        }
    }
}

Use TcpClient to write to/read from a server

using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
public class MainClass
{
    private static void Main()
    {
        using (TcpClient client = new TcpClient())
        {
            Console.WriteLine("Attempting to connect to the server ","on port 8000.");
            client.Connect(IPAddress.Parse("127.0.0.1"), 8000);
            using (NetworkStream networkStream = client.GetStream())
            {
                using (BinaryWriter writer = new BinaryWriter(networkStream))
                {
                    writer.Write("info");
                    using (BinaryReader reader = new BinaryReader(networkStream))
                    {
                        Console.WriteLine(reader.ReadString());
                    }
                }
            }
        }
    }
}

Write string to server

using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;

   public class MainClass
   {
      public static int Main()
      {
         
         string serverName = "localhost";
         Console.WriteLine( "Connecting to {0}", serverName );
         TcpClient tcpSocket = new TcpClient( serverName, 65000 );
         NetworkStream streamToServer = tcpSocket.GetStream();
         string message = "Hello";
         Console.WriteLine("Sending {0} to server.", message );
         System.IO.StreamWriter writer = new System.IO.StreamWriter( streamToServer );
         writer.WriteLine( message );
         writer.Flush();
         System.IO.StreamReader reader = new System.IO.StreamReader( streamToServer );
         string strResponse = reader.ReadLine();
         Console.WriteLine( "Received: {0}", strResponse );
         streamToServer.Close();
         return 0;
      }
   }