Csharp/C Sharp by API/System.Net.Sockets/Socket

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp )

  

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MainClass
{
  const int echoPort = 7;
  [STAThread]
  static void Main( string[] args )
  {
    Socket s = new Socket( AddressFamily.InterNetwork, 
      SocketType.Stream, 
      ProtocolType.Tcp );
    s.Connect( new IPEndPoint( IPAddress.Loopback, echoPort ) );
    UTF8Encoding enc = new UTF8Encoding();
    s.Send( enc.GetBytes( "test message" ) );
    Byte[] buff = new Byte[ 1024 ];
    s.Receive( buff );
    System.Console.WriteLine( enc.GetString( buff ) );
  }
}


Socket.AddressFamily

  
using System;
using System.Net;
using System.Net.Sockets;
class MainClass
{
   public static void Main()
   {
      IPAddress ia = IPAddress.Parse("127.0.0.1");
      IPEndPoint ie = new IPEndPoint(ia, 8000);
      Socket test = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      Console.WriteLine("AddressFamily: {0}",test.AddressFamily);
      Console.WriteLine("SocketType: {0}",test.SocketType);
      Console.WriteLine("ProtocolType: {0}",test.ProtocolType);

      test.Close();
   }
}


Socket.Bind(IPEndPoint ip)

  
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MainClass
{
   public static void Main()
   {
      IPEndPoint ip = new IPEndPoint(IPAddress.Any,9999);
      Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
      socket.Bind(ip);
      socket.Listen(10);
      Console.WriteLine("Waiting for a client...");
      Socket client = socket.Accept();
      IPEndPoint clientep =(IPEndPoint)client.RemoteEndPoint;
      Console.WriteLine("Connected with {0} at port {1}",clientep.Address, clientep.Port);
      
      string welcome = "Welcome";
      byte[] data = new byte[1024];
      data = Encoding.ASCII.GetBytes(welcome);
      client.Send(data, data.Length,SocketFlags.None);
      Console.WriteLine("Disconnected from {0}",clientep.Address);
      client.Close();
      socket.Close();
   }
}


Socket.Blocking

  
using System;
using System.Net;
using System.Net.Sockets;
class MainClass
{
   public static void Main()
   {
      IPAddress ia = IPAddress.Parse("127.0.0.1");
      IPEndPoint ie = new IPEndPoint(ia, 8000);
      Socket test = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      Console.WriteLine("Blocking: {0}", test.Blocking);
      test.Blocking = false;
      Console.WriteLine("new Blocking: {0}",test.Blocking);
      Console.WriteLine("Connected: {0}", test.Connected);
      test.Close();
   }
}


Socket.Connected

  
using System;
using System.Net;
using System.Net.Sockets;
class MainClass
{
   public static void Main()
   {
      IPAddress ia = IPAddress.Parse("127.0.0.1");
      IPEndPoint ie = new IPEndPoint(ia, 8000);
      Socket test = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      Console.WriteLine("Blocking: {0}", test.Blocking);
      test.Blocking = false;
      Console.WriteLine("new Blocking: {0}",test.Blocking);
      Console.WriteLine("Connected: {0}", test.Connected);
      test.Close();
   }
}


Socket.Connect(IPEndPoint ip)

  
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MainClass
{
   public static void Main()
   {
      IPAddress host = IPAddress.Parse("192.168.1.1");
      IPEndPoint hostep = new IPEndPoint(host, 8000);
      Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      try
      {
         sock.Connect(hostep);
      } catch (SocketException e) {
         Console.WriteLine("Problem connecting to host");
         Console.WriteLine(e.ToString());
         sock.Close();
         return;
      }
      sock.Close();
   }
}


Socket.Listen

 
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class StreamTcpSrvr
{
   public static void Main()
   {
      string data;
      IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
      Socket newsock = new Socket(AddressFamily.InterNetwork,
                      SocketType.Stream, ProtocolType.Tcp);
      newsock.Bind(ipep);
      newsock.Listen(10);
      Socket client = newsock.Accept();
      IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
      Console.WriteLine("Connected with {0} at port {1}",
                      newclient.Address, newclient.Port);
      NetworkStream ns = new NetworkStream(client);
      StreamReader sr = new StreamReader(ns);
      StreamWriter sw = new StreamWriter(ns);
      string welcome = "Welcome to my test server";
      sw.WriteLine(welcome);
      sw.Flush();
      while(true)
      {
         try
         {
            data = sr.ReadLine();
         } catch (IOException)
         {
            break;
         }
       
         Console.WriteLine(data);
         sw.WriteLine(data);
         sw.Flush();
      }
      Console.WriteLine("Disconnected from {0}", newclient.Address);
      sw.Close();
      sr.Close();
      ns.Close();
   }
}


Socket.LocalEndPoint

  
using System;
using System.Net;
using System.Net.Sockets;
class MainClass
{
   public static void Main()
   {
      IPAddress ia = IPAddress.Parse("127.0.0.1");
      IPEndPoint ie = new IPEndPoint(ia, 8000);
      Socket test = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      Console.WriteLine("Blocking: {0}", test.Blocking);
      test.Bind(ie);
      IPEndPoint iep = (IPEndPoint)test.LocalEndPoint;
      Console.WriteLine("Local EndPoint: {0}",iep.ToString());
      test.Close();
   }
}


Socket.ProtocolType

  
using System;
using System.Net;
using System.Net.Sockets;
class MainClass
{
   public static void Main()
   {
      IPAddress ia = IPAddress.Parse("127.0.0.1");
      IPEndPoint ie = new IPEndPoint(ia, 8000);
      Socket test = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      Console.WriteLine("AddressFamily: {0}",test.AddressFamily);
      Console.WriteLine("SocketType: {0}",test.SocketType);
      Console.WriteLine("ProtocolType: {0}",test.ProtocolType);

      test.Close();
   }
}


Socket.Receive(byte[] data)

  

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MainClass
{
   public static void Main()
   {
      IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);
      Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
      try
      {
         server.Connect(ip);
      } catch (SocketException e){
         Console.WriteLine("Unable to connect to server.");
         return;
      }
      byte[] data = new byte[1024];
      int receivedDataLength = server.Receive(data);
      string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
      Console.WriteLine(stringData);
      server.Shutdown(SocketShutdown.Both);
      server.Close();
   }
}


Socket.ReceiveFrom

 
/*
C# Network Programming 
by Richard Blum
Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SimpleUdpClient
{
   public static void Main()
   {
      byte[] data = new byte[1024];
      string input, stringData;
      IPEndPoint ipep = new IPEndPoint(
                      IPAddress.Parse("127.0.0.1"), 9050);
      Socket server = new Socket(AddressFamily.InterNetwork,
                     SocketType.Dgram, ProtocolType.Udp);

      string welcome = "Hello, are you there?";
      data = Encoding.ASCII.GetBytes(welcome);
      server.SendTo(data, data.Length, SocketFlags.None, ipep);
      IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
      EndPoint Remote = (EndPoint)sender;
      data = new byte[1024];
      int recv = server.ReceiveFrom(data, ref Remote);
      Console.WriteLine("Message received from {0}:", Remote.ToString());
      Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
      while(true)
      {
         input = Console.ReadLine();
         if (input == "exit")
            break;
         server.SendTo(Encoding.ASCII.GetBytes(input), Remote);
         data = new byte[1024];
         recv = server.ReceiveFrom(data, ref Remote);
         stringData = Encoding.ASCII.GetString(data, 0, recv);
         Console.WriteLine(stringData);
      }
      Console.WriteLine("Stopping client");
      server.Close();
   }
}


Socket.Send(data, data.Length, SocketFlags.None)

 
/*
C# Network Programming 
by Richard Blum
Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SelectTcpClient
{
   public static void Main()
   {
      Socket sock = new Socket(AddressFamily.InterNetwork,
                        SocketType.Stream, ProtocolType.Tcp);
      IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
      byte[] data = new byte[1024];
      string stringData;
      int recv;
      sock.Connect(iep);
      Console.WriteLine("Connected to server");
      recv = sock.Receive(data);
      stringData = Encoding.ASCII.GetString(data, 0, recv);
      Console.WriteLine("Received: {0}", stringData);

      while(true)
      {
         stringData = Console.ReadLine();
         if (stringData == "exit")
            break;
         data = Encoding.ASCII.GetBytes(stringData);
         sock.Send(data, data.Length, SocketFlags.None);
         data = new byte[1024];
         recv = sock.Receive(data);
         stringData = Encoding.ASCII.GetString(data, 0, recv);
         Console.WriteLine("Received: {0}", stringData);
      }
      sock.Close();
   }
}


Socket.Send(String stringValue)

  
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MainClass
{
   public static void Main()
   {
      IPAddress host = IPAddress.Parse("192.168.1.1");
      IPEndPoint hostep = new IPEndPoint(host, 8000);
      Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      try
      {
         sock.Connect(hostep);
      } catch (SocketException e) {
         Console.WriteLine("Problem connecting to host");
         Console.WriteLine(e.ToString());
         sock.Close();
         return;
      }
      try
      {
         sock.Send(Encoding.ASCII.GetBytes("testing"));
      } catch (SocketException e) {
          Console.WriteLine("Problem sending data");
          Console.WriteLine( e.ToString());
          sock.Close();
          return;
      }
      sock.Close();
   }
}


Socket.sentTo

  
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MultiSend
{
   public static void Main()
   {
      Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
      IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
      
      byte[] data = Encoding.ASCII.GetBytes("This is a test message");
      server.SendTo(data, iep);
      server.Close();
   }
}


Socket.SocketType

  
using System;
using System.Net;
using System.Net.Sockets;
class MainClass
{
   public static void Main()
   {
      IPAddress ia = IPAddress.Parse("127.0.0.1");
      IPEndPoint ie = new IPEndPoint(ia, 8000);
      Socket test = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      Console.WriteLine("AddressFamily: {0}",test.AddressFamily);
      Console.WriteLine("SocketType: {0}",test.SocketType);
      Console.WriteLine("ProtocolType: {0}",test.ProtocolType);

      test.Close();
   }
}