Showing posts with label Console to internet. Show all posts
Showing posts with label Console to internet. Show all posts

Monday, June 1, 2009

Communicating with inernet from Console application

Following code can be used to communicate with internet from a console application.

using System;
using System.Security.Cryptography;
using System.Text;
using System.Net.Sockets;
using System.IO;

namespace GirderInternetEventClient
{

public class GirderInternetEventClient
{
public GirderInternetEventClient()
{

}

public static void Main(string[] args)
{

if (args.Length == 4)
{
sendEventString(args[0], int.Parse(args[1]), args[2], args[3]);
return;
}

Console.WriteLine("Girder Internet Event Client");

Console.Write("Enter host [localhost]: ");

string host = Console.ReadLine();

if (host.Equals("")) host = "localhost";

Console.Write("Enter port [1024]: ");

string port = Console.ReadLine();

if (port.Equals("")) port = "1024";

Console.Write("Enter password [NewDefPWD]: ");

string password = Console.ReadLine();

if (password.Equals("")) password = "NewDefPWD";

Console.Write("Enter event [CR ends]: ");

string event_string = Console.ReadLine();

while (!event_string.Equals(""))
{
sendEventString(host, int.Parse(port), password, event_string);

Console.Write("Enter event [CR ends]: ");

event_string = Console.ReadLine();
}

Console.WriteLine("Done");
}

public static String getHexString(byte[] bytes)
{
String hex_string = "";
byte[] item = { 0 };

for (int i = 0; i < bytes.Length; i++)
{
item[0] = bytes[i];
hex_string += BitConverter.ToString(item);
}

return hex_string;
}

public static String getMD5String(String str)
{
MD5 md5 = new MD5CryptoServiceProvider();

byte[] result = md5.ComputeHash((new UTF8Encoding()).GetBytes(str));

return getHexString(result);
}

public static void sendEventString(String hostname, int port, String password, String event_string)
{
TcpClient tcpClient = new TcpClient();

try
{
tcpClient.Connect(hostname, port);

NetworkStream networkStream = tcpClient.GetStream();
StreamReader input = new StreamReader(networkStream);
StreamWriter output = new StreamWriter(networkStream);
output.AutoFlush = true;

output.WriteLine("quintessence");
String cookie = input.ReadLine();
output.WriteLine(getMD5String(cookie + ":" + password));
String accept_result = input.ReadLine();

if (accept_result.Equals("accept"))
{
output.WriteLine(event_string);

output.WriteLine("close");
}

}
finally
{
tcpClient.Close();
}
}
}
}