Creating Socket Connections : TcpClient « Network « C# / CSharp Tutorial






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








33.7.TcpClient
33.7.1.Creating Socket Connections
33.7.2.Use a NetworkStream to read from a server
33.7.3.Create NetworkStream from TcpClient
33.7.4.use TcpClient to connect to a server
33.7.5.Create BinaryWriter and BinaryReader from TcpClient
33.7.6.Use TcpClient to write to/read from a server
33.7.7.Network Client and StreamReader
33.7.8.Network Client with TcpClient and NetworkStream
33.7.9.Write string to server
33.7.10.Read csv from finance.yahoo.com with TcpClient