Csharp/CSharp Tutorial/Network/Socket — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Текущая версия на 15:20, 26 мая 2010
Содержание
Bind Socket with an IPEndPoint
<source lang="csharp">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(); }
}</source>
Blocking: True Local EndPoint: 127.0.0.1:8000
Display the connected client IP address
<source lang="csharp">using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; class MainClass {
public static void Main() { string data; IPEndPoint ip = new IPEndPoint(IPAddress.Any, 9999); Socket socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); socket.Bind(ip); socket.Listen(10); Socket client = socket.Accept(); IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("Connected with {0} at port {1}",newclient.Address, newclient.Port); }
}</source>
Socket: AddressFamily, SocketType and ProtocolType
<source lang="csharp">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(); }
}</source>
AddressFamily: InterNetwork SocketType: Stream ProtocolType: Tcp
Socket: Blocking and Connected
<source lang="csharp">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(); }
}</source>
Blocking: True new Blocking: False Connected: False
Socket: sentTo
<source lang="csharp">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(); }
}</source>