Csharp/C Sharp/Network/TCP Client
Содержание
Async Tcp Client
<source lang="csharp"> /* C# Network Programming by Richard Blum Publisher: Sybex ISBN: 0782141765
- /
using System; using System.Drawing; using System.Net; using System.Net.Sockets; using System.Text; using System.Windows.Forms;
public class AsyncTcpClient : Form {
private TextBox newText; private TextBox conStatus; private ListBox results; private Socket client; private byte[] data = new byte[1024]; private int size = 1024; public AsyncTcpClient() { Text = "Asynchronous TCP Client"; Size = new Size(400, 380); Label label1 = new Label(); label1.Parent = this; label1.Text = "Enter text string:"; label1.AutoSize = true; label1.Location = new Point(10, 30); newText = new TextBox(); newText.Parent = this; newText.Size = new Size(200, 2 * Font.Height); newText.Location = new Point(10, 55); results = new ListBox(); results.Parent = this; results.Location = new Point(10, 85); results.Size = new Size(360, 18 * Font.Height); Label label2 = new Label(); label2.Parent = this; label2.Text = "Connection Status:"; label2.AutoSize = true; label2.Location = new Point(10, 330); conStatus = new TextBox(); conStatus.Parent = this; conStatus.Text = "Disconnected"; conStatus.Size = new Size(200, 2 * Font.Height); conStatus.Location = new Point(110, 325); Button sendit = new Button(); sendit.Parent = this; sendit.Text = "Send"; sendit.Location = new Point(220,52); sendit.Size = new Size(5 * Font.Height, 2 * Font.Height); sendit.Click += new EventHandler(ButtonSendOnClick); Button connect = new Button(); connect.Parent = this; connect.Text = "Connect"; connect.Location = new Point(295, 20); connect.Size = new Size(6 * Font.Height, 2 * Font.Height); connect.Click += new EventHandler(ButtonConnectOnClick); Button discon = new Button(); discon.Parent = this; discon.Text = "Disconnect"; discon.Location = new Point(295,52); discon.Size = new Size(6 * Font.Height, 2 * Font.Height); discon.Click += new EventHandler(ButtonDisconOnClick); } void ButtonConnectOnClick(object obj, EventArgs ea) { conStatus.Text = "Connecting..."; Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock); } void ButtonSendOnClick(object obj, EventArgs ea) { byte[] message = Encoding.ASCII.GetBytes(newText.Text); newText.Clear(); client.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(SendData), client); } void ButtonDisconOnClick(object obj, EventArgs ea) { client.Close(); conStatus.Text = "Disconnected"; } void Connected(IAsyncResult iar) { client = (Socket)iar.AsyncState; try { client.EndConnect(iar); conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString(); client.BeginReceive(data, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), client); } catch (SocketException) { conStatus.Text = "Error connecting"; } } void ReceiveData(IAsyncResult iar) { Socket remote = (Socket)iar.AsyncState; int recv = remote.EndReceive(iar); string stringData = Encoding.ASCII.GetString(data, 0, recv); results.Items.Add(stringData); } void SendData(IAsyncResult iar) { Socket remote = (Socket)iar.AsyncState; int sent = remote.EndSend(iar); remote.BeginReceive(data, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), remote); } public static void Main() { Application.Run(new AsyncTcpClient()); }
}
</source>
Bad Tcp Client
<source lang="csharp"> /* C# Network Programming by Richard Blum Publisher: Sybex ISBN: 0782141765
- /
using System; using System.Net; using System.Net.Sockets; using System.Text; public class BadTcpClient {
public static void Main() { byte[] data = new byte[1024]; string stringData; IPEndPoint ipep = new IPEndPoint( IPAddress.Parse("127.0.0.1"), 9050); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { server.Connect(ipep); } catch (SocketException e) { Console.WriteLine("Unable to connect to server."); Console.WriteLine(e.ToString()); return; }
int recv = server.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); server.Send(Encoding.ASCII.GetBytes("message 1")); server.Send(Encoding.ASCII.GetBytes("message 2")); server.Send(Encoding.ASCII.GetBytes("message 3")); server.Send(Encoding.ASCII.GetBytes("message 4")); server.Send(Encoding.ASCII.GetBytes("message 5")); Console.WriteLine("Disconnecting from server..."); server.Shutdown(SocketShutdown.Both); server.Close(); }
}
</source>
Employee Client
<source lang="csharp"> /* C# Network Programming by Richard Blum Publisher: Sybex ISBN: 0782141765
- /
using System; using System.Text; using System.Net; using System.Net.Sockets;
public class EmployeeClient {
public static void Main() { Employee emp1 = new Employee(); Employee emp2 = new Employee(); TcpClient client; emp1.EmployeeID = 1; emp1.LastName = "Blum"; emp1.FirstName = "Katie Jane"; emp1.YearsService = 12; emp1.Salary = 35000.50; emp2.EmployeeID = 2; emp2.LastName = "Blum"; emp2.FirstName = "Jessica"; emp2.YearsService = 9; emp2.Salary = 23700.30; try { client = new TcpClient("127.0.0.1", 9050); } catch (SocketException) { Console.WriteLine("Unable to connect to server"); return; } NetworkStream ns = client.GetStream(); byte[] data = emp1.GetBytes(); int size = emp1.size; byte[] packsize = new byte[2]; Console.WriteLine("packet size = {0}", size); packsize = BitConverter.GetBytes(size); ns.Write(packsize, 0, 2); ns.Write(data, 0, size); ns.Flush(); data = emp2.GetBytes(); size = emp2.size; packsize = new byte[2]; Console.WriteLine("packet size = {0}", size); packsize = BitConverter.GetBytes(size); ns.Write(packsize, 0, 2); ns.Write(data, 0, size); ns.Flush(); ns.Close(); client.Close(); }
}
public class Employee
{
public int EmployeeID; private int LastNameSize; public string LastName; private int FirstNameSize; public string FirstName; public int YearsService; public double Salary; public int size; public Employee() { } public Employee(byte[] data) { int place = 0; EmployeeID = BitConverter.ToInt32(data, place); place += 4; LastNameSize = BitConverter.ToInt32(data, place); place += 4; LastName = Encoding.ASCII.GetString(data, place, LastNameSize); place = place + LastNameSize; FirstNameSize = BitConverter.ToInt32(data, place); place += 4; FirstName = Encoding.ASCII.GetString(data, place, FirstNameSize); place += FirstNameSize; YearsService = BitConverter.ToInt32(data, place); place += 4; Salary = BitConverter.ToDouble(data, place); } public byte[] GetBytes() { byte[] data = new byte[1024]; int place = 0; Buffer.BlockCopy(BitConverter.GetBytes(EmployeeID), 0, data, place, 4); place += 4; Buffer.BlockCopy(BitConverter.GetBytes(LastName.Length), 0, data, place, 4); place += 4; Buffer.BlockCopy(Encoding.ASCII.GetBytes(LastName), 0, data, place, LastName.Length); place += LastName.Length; Buffer.BlockCopy(BitConverter.GetBytes(FirstName.Length), 0, data, place, 4); place += 4; Buffer.BlockCopy(Encoding.ASCII.GetBytes(FirstName), 0, data, place, FirstName.Length); place += FirstName.Length; Buffer.BlockCopy(BitConverter.GetBytes(YearsService), 0, data, place, 4); place += 4; Buffer.BlockCopy(BitConverter.GetBytes(Salary), 0, data, place, 8); place += 8; size = place; return data; }
}
</source>
Fixed Tcp Client
<source lang="csharp"> /* C# Network Programming by Richard Blum Publisher: Sybex ISBN: 0782141765
- /
using System; using System.Net; using System.Net.Sockets; using System.Text; public class FixedTcpClient {
private static int SendData(Socket s, byte[] data) { int total = 0; int size = data.Length; int dataleft = size; int sent; while (total < size) { sent = s.Send(data, total, dataleft, SocketFlags.None); total += sent; dataleft -= sent; } return total; } private static byte[] ReceiveData(Socket s, int size) { int total = 0; int dataleft = size; byte[] data = new byte[size]; int recv; while(total < size) { recv = s.Receive(data, total, dataleft, 0); if (recv == 0) { data = Encoding.ASCII.GetBytes("exit "); break; } total += recv; dataleft -= recv; } return data; } public static void Main() { byte[] data = new byte[1024]; int sent; IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { server.Connect(ipep); } catch (SocketException e) { Console.WriteLine("Unable to connect to server."); Console.WriteLine(e.ToString()); return; } int recv = server.Receive(data); string stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); sent = SendData(server, Encoding.ASCII.GetBytes("message 1")); sent = SendData(server, Encoding.ASCII.GetBytes("message 2")); sent = SendData(server, Encoding.ASCII.GetBytes("message 3")); sent = SendData(server, Encoding.ASCII.GetBytes("message 4")); sent = SendData(server, Encoding.ASCII.GetBytes("message 5")); Console.WriteLine("Disconnecting from server..."); server.Shutdown(SocketShutdown.Both); server.Close(); }
}
</source>
Network Order Client
<source lang="csharp"> /* C# Network Programming by Richard Blum Publisher: Sybex ISBN: 0782141765
- /
using System; using System.Net; using System.Net.Sockets; using System.Text; public class NetworkOrderClient {
public static void Main() { byte[] data = new byte[1024]; string stringData; TcpClient server; try { server = new TcpClient("127.0.0.1", 9050); } catch (SocketException) { Console.WriteLine("Unable to connect to server"); return; } NetworkStream ns = server.GetStream(); int recv = ns.Read(data, 0, data.Length); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); short test1 = 45; int test2 = 314159; long test3 = -123456789033452; short test1b = IPAddress.HostToNetworkOrder(test1); data = BitConverter.GetBytes(test1b); Console.WriteLine("sending test1 = {0}", test1); ns.Write(data, 0, data.Length); ns.Flush(); int test2b = IPAddress.HostToNetworkOrder(test2); data = BitConverter.GetBytes(test2b); Console.WriteLine("sending test2 = {0}", test2); ns.Write(data, 0, data.Length); ns.Flush(); long test3b = IPAddress.HostToNetworkOrder(test3); data = BitConverter.GetBytes(test3b); Console.WriteLine("sending test3 = {0}", test3); ns.Write(data, 0, data.Length); ns.Flush(); ns.Close(); server.Close(); }
}
</source>
Network Stream Tcp Client
<source lang="csharp"> /* C# Network Programming by Richard Blum Publisher: Sybex ISBN: 0782141765
- /
using System; using System.Net; using System.Net.Sockets; using System.Text; public class NetworkStreamTcpClient {
public static void Main() { byte[] data = new byte[1024]; string input, stringData; int recv; IPEndPoint ipep = new IPEndPoint( IPAddress.Parse("127.0.0.1"), 9050); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { server.Connect(ipep); } catch (SocketException e) { Console.WriteLine("Unable to connect to server."); Console.WriteLine(e.ToString()); return; } NetworkStream ns = new NetworkStream(server); if (ns.CanRead) { recv = ns.Read(data, 0, data.Length); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); } else { Console.WriteLine("Error: Can"t read from this socket"); ns.Close(); server.Close(); return; } while(true) { input = Console.ReadLine(); if (input == "exit") break; if (ns.CanWrite) { ns.Write(Encoding.ASCII.GetBytes(input), 0, input.Length); ns.Flush(); } recv = ns.Read(data, 0, data.Length); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); } Console.WriteLine("Disconnecting from server..."); ns.Close(); server.Shutdown(SocketShutdown.Both); server.Close(); }
}
</source>
Picky Tcp Client
<source lang="csharp"> /* C# Network Programming by Richard Blum Publisher: Sybex ISBN: 0782141765
- /
using System; using System.Net; using System.Net.Sockets; using System.Security; using System.Security.Permissions; using System.Text; [SocketPermission(SecurityAction.Deny, Access="Connect", Host="127.0.0.1",
Port="All", Transport="All")]
[SocketPermission(SecurityAction.Deny, Access="Connect", Host="192.168.0.2",
Port="All", Transport="All")]
[SocketPermission(SecurityAction.Deny, Access="Connect", Host="192.168.1.100",
Port="80", Transport="All")]
public class PickyTcpClient {
public static void Main() { byte[] data = new byte[1024]; string input, stringData; TcpClient server = null; Console.Write("Enter a host to connect to: "); string stringHost = Console.ReadLine(); try { server = new TcpClient(stringHost, 9050); } catch (SocketException) { Console.WriteLine("Unable to connect to server"); return; } catch (SecurityException) { Console.WriteLine( "Sorry, you are restricted from connecting to this server"); return; } NetworkStream ns = server.GetStream(); int recv = ns.Read(data, 0, data.Length); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); while(true) { input = Console.ReadLine(); if (input == "exit") break; ns.Write(Encoding.ASCII.GetBytes(input), 0, input.Length); ns.Flush(); data = new byte[1024]; recv = ns.Read(data, 0, data.Length); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); } Console.WriteLine("Disconnecting from server..."); ns.Close(); server.Close(); }
}
</source>
Select Tcp Client
<source lang="csharp"> /* 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(); }
}
</source>
Simple Tcp Client
<source lang="csharp"> /* C# Network Programming by Richard Blum Publisher: Sybex ISBN: 0782141765
- /
using System; using System.Net; using System.Net.Sockets; using System.Text; public class SimpleTcpClient {
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.Stream, ProtocolType.Tcp); try { server.Connect(ipep); } catch (SocketException e) { Console.WriteLine("Unable to connect to server."); Console.WriteLine(e.ToString()); return; }
int recv = server.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); while(true) { input = Console.ReadLine(); if (input == "exit") break; server.Send(Encoding.ASCII.GetBytes(input)); data = new byte[1024]; recv = server.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); } Console.WriteLine("Disconnecting from server..."); server.Shutdown(SocketShutdown.Both); server.Close(); }
}
</source>
Stream Tcp Client
<source lang="csharp"> /* C# Network Programming by Richard Blum Publisher: Sybex ISBN: 0782141765
- /
using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; public class StreamTcpClient {
public static void Main() { string data; string input; IPEndPoint ipep = new IPEndPoint( IPAddress.Parse("127.0.0.1"), 9050); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { server.Connect(ipep); } catch (SocketException e) { Console.WriteLine("Unable to connect to server."); Console.WriteLine(e.ToString()); return; }
NetworkStream ns = new NetworkStream(server); StreamReader sr = new StreamReader(ns); StreamWriter sw = new StreamWriter(ns); data = sr.ReadLine(); Console.WriteLine(data); while(true) { input = Console.ReadLine(); if (input == "exit") break; sw.WriteLine(input); sw.Flush(); data = sr.ReadLine(); Console.WriteLine(data); } Console.WriteLine("Disconnecting from server..."); sr.Close(); sw.Close(); ns.Close(); server.Shutdown(SocketShutdown.Both); server.Close(); }
}
</source>
Tcp Client Sample
<source lang="csharp"> /* C# Network Programming by Richard Blum Publisher: Sybex ISBN: 0782141765
- /
using System; using System.Net; using System.Net.Sockets; using System.Text; public class TcpClientSample {
public static void Main() { byte[] data = new byte[1024]; string input, stringData; TcpClient server; try { server = new TcpClient("127.0.0.1", 9050); } catch (SocketException) { Console.WriteLine("Unable to connect to server"); return; } NetworkStream ns = server.GetStream(); int recv = ns.Read(data, 0, data.Length); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); while(true) { input = Console.ReadLine(); if (input == "exit") break; ns.Write(Encoding.ASCII.GetBytes(input), 0, input.Length); ns.Flush(); data = new byte[1024]; recv = ns.Read(data, 0, data.Length); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); } Console.WriteLine("Disconnecting from server..."); ns.Close(); server.Close(); }
}
</source>
Uses a TcpClient to handle HTTP
<source lang="csharp"> using System; using System.Text; using System.IO; using System.Net.Sockets;
public class TryTcp {
public static void Main(String [] args) { TcpClient client = new TcpClient("www.nfex.ru", 80); NetworkStream stream = client.GetStream(); byte[] send = Encoding.ASCII.GetBytes("GET HTTP/1.0 \r\n\r\n"); stream.Write(send, 0, send.Length); byte[] bytes = new byte[client.ReceiveBufferSize]; int count = stream.Read(bytes, 0, (int)client.ReceiveBufferSize); String data = Encoding.ASCII.GetString(bytes); char[] unused = {(char)data[count]}; Console.WriteLine(data.TrimEnd(unused)); stream.Close(); client.Close(); }
}
</source>
Var Tcp Client
<source lang="csharp"> /* C# Network Programming by Richard Blum Publisher: Sybex ISBN: 0782141765
- /
using System; using System.Net; using System.Net.Sockets; using System.Text; public class VarTcpClient {
private static int SendVarData(Socket s, byte[] data) { int total = 0; int size = data.Length; int dataleft = size; int sent; byte[] datasize = new byte[4]; datasize = BitConverter.GetBytes(size); sent = s.Send(datasize); while (total < size) { sent = s.Send(data, total, dataleft, SocketFlags.None); total += sent; dataleft -= sent; } return total; } private static byte[] ReceiveVarData(Socket s) { int total = 0; int recv; byte[] datasize = new byte[4]; recv = s.Receive(datasize, 0, 4, 0); int size = BitConverter.ToInt32(datasize, 0); int dataleft = size; byte[] data = new byte[size]; while(total < size) { recv = s.Receive(data, total, dataleft, 0); if (recv == 0) { data = Encoding.ASCII.GetBytes("exit "); break; } total += recv; dataleft -= recv; } return data; } public static void Main() { byte[] data = new byte[1024]; int sent; IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { server.Connect(ipep); } catch (SocketException e) { Console.WriteLine("Unable to connect to server."); Console.WriteLine(e.ToString()); return; } data = ReceiveVarData(server); string stringData = Encoding.ASCII.GetString(data); Console.WriteLine(stringData); string message1 = "This is the first test"; string message2 = "A short test"; string message3 = "This string is an even longer test. The quick brown fox jumps over the lazy dog."; string message4 = "a"; string message5 = "The last test"; sent = SendVarData(server, Encoding.ASCII.GetBytes(message1)); sent = SendVarData(server, Encoding.ASCII.GetBytes(message2)); sent = SendVarData(server, Encoding.ASCII.GetBytes(message3)); sent = SendVarData(server, Encoding.ASCII.GetBytes(message4)); sent = SendVarData(server, Encoding.ASCII.GetBytes(message5)); Console.WriteLine("Disconnecting from server..."); server.Shutdown(SocketShutdown.Both); server.Close(); }
}
</source>