Csharp/CSharp Tutorial/Network/Socket Client — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 15:20, 26 мая 2010
Содержание
Echo Client without message encoding
<source lang="csharp">using System; using System.IO; using System.Net.Sockets; class MainClass {
const int echoPort = 7; [STAThread] static void Main(string[] args) { using ( TcpClient tc = new TcpClient( "localhost", echoPort ) ) { NetworkStream ns = tc.GetStream(); StreamWriter sw = new StreamWriter( ns ); StreamReader sr = new StreamReader( ns ); sw.WriteLine( "test message" ); sw.Flush(); System.Console.WriteLine( sr.ReadLine() ); } }
}</source>
Echo Client with UTF8 Encoding
<source lang="csharp">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 ) ); }
}</source>
GUI based Tcp Client
<source lang="csharp">/* Quote from C# Network Programming
- Paperback: 656 pages
- Publisher: Sybex (November 26, 2002)
- Language: English
- ISBN-10: 0782141765
- ISBN-13: 978-0782141764
- /
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>
Send data using Socket
<source lang="csharp">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(); }
}</source>
Simple Tcp Client: receive data from server
<source lang="csharp">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(); }
}</source>
Simple Tcp Client: send data to the server
<source lang="csharp">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; } Console.WriteLine("Type "exit" to exit."); while(true) { string input = Console.ReadLine(); if (input == "exit") break; server.Send(Encoding.ASCII.GetBytes(input)); 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(); }
}</source>
Simple Tcp server: send data to the client
<source lang="csharp">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(); }
}</source>
Socket connection
<source lang="csharp">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(); }
}</source>