The contents of this page are licensed under the following license
.Net C# Sockets
Daytime client |
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; namespace DayTime { public partial class Form1 : Form { private Form obj; delegate void setThreadedTextBoxCallback(String text); delegate void setThreadedStatusLabelCallback(String text); delegate void setThreadedButtonCallback(bool status); public Form1() { InitializeComponent(); this.obj = this; } private void setThreadedTextBox(String text) { if (this.textBoxDate.InvokeRequired) { setThreadedTextBoxCallback textBoxCallback = new setThreadedTextBoxCallback(setThreadedTextBox); this.obj.Invoke(textBoxCallback, text); } else { this.textBoxDate.Text = text; } } private void setThreadedStatusLabel(String text) { if (this.statusStrip.InvokeRequired) { setThreadedStatusLabelCallback statusLabelCallback = new setThreadedStatusLabelCallback(setThreadedStatusLabel); this.obj.Invoke(statusLabelCallback, text); } else { this.toolStripStatusLabel1.Text = text; } } private void setThreadedButton(bool status) { if (this.buttonGetDate.InvokeRequired) { setThreadedButtonCallback buttonCallback = new setThreadedButtonCallback(setThreadedButton); this.obj.Invoke(buttonCallback, status); } else { this.buttonGetDate.Enabled = status; } } private void ReceiveCallback(IAsyncResult ar) { try { /* retrieve the SocketStateObject */ SocketStateObject state = (SocketStateObject)ar.AsyncState; Socket socketFd = state.m_SocketFd; /* read data */ int size = socketFd.EndReceive(ar); if (size > 0) { state.m_StringBuilder.Append(Encoding.ASCII.GetString(state.m_DataBuf, 0, size)); /* get the rest of the data */ socketFd.BeginReceive(state.m_DataBuf, 0, SocketStateObject.BUF_SIZE, 0, new AsyncCallback(ReceiveCallback), state); } else { /* all the data has arrived */ if (state.m_StringBuilder.Length > 1) { setThreadedTextBox(state.m_StringBuilder.ToString()); setThreadedStatusLabel("Done."); setThreadedButton(true); /* shutdown and close socket */ socketFd.Shutdown(SocketShutdown.Both); socketFd.Close(); } } } catch (Exception exc) { MessageBox.Show("Exception:\t\n" + exc.Message.ToString()); setThreadedStatusLabel("Check \"Server Info\" and try again!"); setThreadedButton(true); } } private void ConnectCallback(IAsyncResult ar) { try { /* retrieve the socket from the state object */ Socket socketFd = (Socket) ar.AsyncState; /* complete the connection */ socketFd.EndConnect(ar); /* create the SocketStateObject */ SocketStateObject state = new SocketStateObject(); state.m_SocketFd = socketFd; setThreadedStatusLabel("Wait! Reading..."); /* begin receiving the data */ socketFd.BeginReceive(state.m_DataBuf, 0, SocketStateObject.BUF_SIZE, 0, new AsyncCallback(ReceiveCallback), state); } catch (Exception exc) { MessageBox.Show("Exception:\t\n" + exc.Message.ToString()); setThreadedStatusLabel("Check \"Server Info\" and try again!"); setThreadedButton(true); } } private void GetHostEntryCallback(IAsyncResult ar) { try { IPHostEntry hostEntry = null; IPAddress[] addresses = null; Socket socketFd = null; IPEndPoint endPoint = null; /* complete the DNS query */ hostEntry = Dns.EndGetHostEntry(ar); addresses = hostEntry.AddressList; /* create a socket */ socketFd = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); /* remote endpoint for the socket */ endPoint = new IPEndPoint(addresses[0], Int32.Parse(this.textBoxPort.Text.ToString())); setThreadedStatusLabel("Wait! Connecting..."); /* connect to the server */ socketFd.BeginConnect(endPoint, new AsyncCallback(ConnectCallback), socketFd); } catch (Exception exc) { MessageBox.Show("Exception:\t\n" + exc.Message.ToString()); setThreadedStatusLabel("Check \"Server Info\" and try again!"); setThreadedButton(true); } } private void buttonGetDate_Click(object sender, EventArgs e) { try { setThreadedButton(false); setThreadedTextBox(""); setThreadedStatusLabel("Wait! DNS query..."); if (this.textBoxAddr.Text.Length > 0 && this.textBoxPort.Text.Length > 0) { /* get DNS host information */ Dns.BeginGetHostEntry(this.textBoxAddr.Text.ToString(), new AsyncCallback(GetHostEntryCallback), null); } else { if (this.textBoxAddr.Text.Length <= 0) MessageBox.Show("No server address!"); else if (this.textBoxPort.Text.Length <= 0) MessageBox.Show("No server port number!"); setThreadedButton(true); setThreadedStatusLabel("Check \"Server Info\" and try again!"); } } catch (Exception exc) { MessageBox.Show("Exception:\t\n" + exc.Message.ToString()); setThreadedStatusLabel("Check \"Server Info\" and try again!"); setThreadedButton(true); } } } public class SocketStateObject { public const int BUF_SIZE = 1024; public byte[] m_DataBuf = new byte[BUF_SIZE]; public StringBuilder m_StringBuilder = new StringBuilder(); public Socket m_SocketFd = null; } } |
Daytime server |
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.Globalization; namespace DayTimeServer { class Program { private const int SERVER_PORT = 1234; private const int QUEUE_SIZE = 5; private static ManualResetEvent m_AcceptDone = new ManualResetEvent(false); private static void SendCallback(IAsyncResult ar) { try { /* retrieve the socket from the ar object */ Socket socketFd = (Socket)ar.AsyncState; /* end pending asynchronous send */ int bytesSent = socketFd.EndSend(ar); Console.WriteLine("\t\tSent {0} bytes to the client\n\tEND connection", bytesSent); /* shutdown and close socket */ socketFd.Shutdown(SocketShutdown.Both); socketFd.Close(); } catch (Exception exc) { Console.WriteLine(exc.Message.ToString()); } } private static void SendDate(Socket socketFd) { try { /* get system date and time */ Thread.CurrentThread.CurrentCulture = new CultureInfo("pl-PL"); DateTime dateTime = DateTime.Now; byte[] dataBuf = Encoding.ASCII.GetBytes(dateTime.ToString()); /* begin sending the date */ socketFd.BeginSend(dataBuf, 0, dataBuf.Length, 0, new AsyncCallback(SendCallback), socketFd); } catch (Exception exc) { Console.WriteLine(exc.Message.ToString()); } } private static void AcceptCallback(IAsyncResult ar) { try { /* get the socket that handles the client request */ Socket socketFd = (Socket) ar.AsyncState; Socket socketNew = socketFd.EndAccept(ar); /* the main socket is now free */ m_AcceptDone.Set(); Console.WriteLine("\tNEW connection"); SendDate(socketNew); } catch (Exception exc) { Console.WriteLine(exc.Message.ToString()); } } private static void RunServer() { Socket socketFd = null; IPEndPoint endPoint = null; try { /* create a socket */ socketFd = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); /* local endpoint for the socket */ endPoint = new IPEndPoint(IPAddress.Any, SERVER_PORT); /* bind the socket to the local endpoint */ socketFd.Bind(endPoint); /* specify queue size */ socketFd.Listen(QUEUE_SIZE); while (true) { m_AcceptDone.Reset(); Console.WriteLine("Waiting for a connection..."); /* block for connection request */ socketFd.BeginAccept(new AsyncCallback(AcceptCallback), socketFd); m_AcceptDone.WaitOne(); } } catch (Exception exc) { Console.WriteLine(exc.Message.ToString()); } finally { /* shutdown and close socket */ socketFd.Shutdown(SocketShutdown.Both); socketFd.Close(); } } static void Main(string[] args) { try { Console.WriteLine("START"); RunServer(); } catch (Exception exc) { Console.WriteLine(exc.Message.ToString()); } } } } |
October, 24th 2006 © Michał Kalewski