using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; namespace CurrencyServer { class Program { public static void Main() { Dictionary rates = new Dictionary(); // put some sample data into dictionary object. Values are not accurate and important rates.Add("usd", 47.5); rates.Add("eur", 60.4); rates.Add("ukp", 78.8); // create a server socket with port number 2000 TcpListener l = new TcpListener(2000); l.Start(); // start listening for client requests Console.WriteLine("Server has started.Waiting for clients..."); while (true) { TcpClient c = l.AcceptTcpClient(); // wait and accept client request Console.WriteLine("Opened connection with client.."); NetworkStream ns = c.GetStream(); // get stream to send and receive data byte[] buf; while (true) { buf = new byte[10]; ns.Read(buf, 0, 10); // read symbol from client // convert bytes to string string symbol = System.Text.Encoding.ASCII.GetString(buf); symbol = symbol.Substring(0, 3); // take only first 3 characters if (symbol == "end") break; // stop if symbol is "end" // find out the corresponding rate byte[] result; try { double value = rates[symbol]; result = System.Text.Encoding.ASCII.GetBytes(value.ToString()); } catch (Exception ex) { result = System.Text.Encoding.ASCII.GetBytes("Invalid"); Console.WriteLine(ex); } ns.Write(result, 0, result.Length); // write rate or error message to client } // close connection ns.Close(); c.Close(); Console.WriteLine("Closed connection with 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.Sockets; namespace CurrencyClient { public partial class Form1 : Form { TcpClient c = null; NetworkStream ns; public CurrencyClient() { InitializeComponent(); // get connection to server c = new TcpClient("localhost", 2000); ns = c.GetStream(); } private void button1_Click(object sender, EventArgs e) { string symbol = ddlSymbols.SelectedItem.ToString(); // get selected symbol from combo box byte[] buf = System.Text.Encoding.ASCII.GetBytes(symbol); ns.Write(buf, 0, symbol.Length); // send symbol to server byte[] rate = new byte[100]; ns.Read(rate, 0, 100); // read data from server lblRate.Text = System.Text.Encoding.ASCII.GetString(rate); // place rate or error message into Label } private void button2_Click(object sender, EventArgs e) { // send "end" to server so that connection to client is closed byte[] buf = System.Text.Encoding.ASCII.GetBytes("end"); ns.Write(buf, 0, 3); this.Dispose(); // close form and application } } }