Introduction
This is my first tutorial on C# programming. I'm not too familiar with the language yet, so please excuse all my small mistakes. The aim of this tutorial is to show how to write an application that connects to a service, opens a network stream for reading and writing, and allows user to type commands or data line-by-line. It can be useful to explore and learn simple network protocols (such as IRC) for writing future, more advanced clients.
The Idea
- Connect to server on specified port.
- Create sending thread.
- If user enters data - send it to the server.
- If application still runs - wait for more data to send.
- 3. Create listening thread.
- If server sends data to client - display or process it.
- If application still runs - wait for more incoming data.
That's how a simple chat-client could look like. User should have at all times the possibility to enter his commands or messages, while application would process all incoming data (for an example - it should display messages on the screen). That requires two independent threads, one "interface" thread, responsible for user input, and second thread which will deal with incoming messages.
The Code
Nothing more to say here.
using System;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace SimpleTCPClient
{
class cApplication
{
private static NetworkStream myStream;
private static TcpClient myClient;
private static byte[] myBuffer;
private static bool bActive = true;
private static void ListenThread()
{
Console.WriteLine("Listening...");
while(bActive)
{
int lData = myStream.Read(myBuffer, 0,
myClient.ReceiveBufferSize);
String myString = Encoding.ASCII.GetString(myBuffer);
myString = myString.Substring(0, lData);
Console.Write(myString);
}
}
private static void SendThread()
{
Console.WriteLine("Sending...");
while(bActive)
{
Console.Write("> ");
String myString = Console.ReadLine() + "\n";
myStream.Write(Encoding.ASCII.GetBytes(
myString.ToCharArray()), 0, myString.Length);
}
}
static void Main(string[] args)
{
Console.Write("Enter server name/address: ");
String strServer = Console.ReadLine();
Console.Write("Enter remote port: ");
String strPort = Console.ReadLine();
myClient = new TcpClient(strServer, Int32.Parse(strPort));
Console.WriteLine("Connected...");
myStream = myClient.GetStream();
myBuffer = new byte[myClient.ReceiveBufferSize];
Thread tidListen = new Thread(new ThreadStart(ListenThread));
Thread tidSend = new Thread(new ThreadStart(SendThread));
Console.WriteLine("Application connected and ready...");
Console.WriteLine("----------------------------------");
tidListen.Start();
tidSend.Start();
}
}
}
The End
It's quite easy to use sockets in C#. The above code lacks exception handling routines and a beautiful interface, but it should give an idea of how to code simple client applications. Maybe in the next tutorial I will write about creating a listening server application and a simple chat client.