If I code a whois server program what functionalities must I supply? - c#

If I code a WHOIS server program, say using languages like C# and Java, what functionalities must I supply?
What I understand is, WHOIS servers listen to the port no. 43. When they receive a command "whois", they respond with various information pertaining to the server itself.
So, it's just a normal TCP/IP server that listens to a special port and serves a specific purpose.
Am I correct?
Whois Client:
using System;
using System.Net.Sockets;
using System.IO;
public class Whois
{
static void Main(string[] args)
{
try
{
TcpClient client = new TcpClient();
client.Connect("localHost", 43);
if (args.Length < 1)
{
Console.WriteLine("Provide more than one Args");
}
else if (args.Length == 1)
{
StreamWriter sw = new StreamWriter(client.GetStream());
StreamReader sr = new StreamReader(client.GetStream());
sw.WriteLine(args[0]);
sw.Flush();
Console.WriteLine(args[0] + " is "+ sr.ReadToEnd());
return;
}
else if (args.Length > 1)
{
StreamWriter sw = new StreamWriter(client.GetStream());
StreamReader sr = new StreamReader(client.GetStream());
string str = "";
foreach (string arg in args)
{
str += arg + " ";
}
sw.WriteLine(str);
sw.Flush();
Console.WriteLine(args[0] + " location changed to be " + args[1]);
sw.Close();
return;
}
else Console.WriteLine("Invalid args ");
return;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
Whois Server:
using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Collections.Generic;
namespace locationserver
{
public class respond
{
static Dictionary<string, string> SavedLocationa = new Dictionary<String, String>();
static void Main(string[] args)
{
runServer();
}
static void runServer()
{
TcpListener listener;
Socket connection;
NetworkStream socketStream;
try
{
listener = new TcpListener(IPAddress.Any, 43);
listener.Start();
Console.WriteLine("server started listening");
while (true)
{
connection = listener.AcceptSocket();
socketStream = new NetworkStream(connection);
Console.WriteLine("Connection Received");
doRequest(socketStream);
socketStream.Close();
connection.Close();
}
}
catch (Exception e)
{
Console.WriteLine("Exception:" + e.ToString());
}
}
static void doRequest(NetworkStream socketStream)
{
try
{
StreamWriter sw = new StreamWriter(socketStream);
StreamReader sr = new StreamReader(socketStream);
String line = sr.ReadLine();
Console.WriteLine("Respond Received:" + line);
String[] sections = line.Split(new char[] { ' ' }, 2);
String names, location;
if (line.Contains("-h0"))
{
Console.WriteLine(" Is ok");
}
else if (line.Contains("-h9"))
{
Console.WriteLine("Hey you're progressing");
}
else if (line.Contains("-h1"))
{
Console.WriteLine("We're Done");
}
if (sections.Length < 1)
{
Console.WriteLine("Too little words was inputted");
}
else if (sections.Length == 1)
{
names = sections[0];
if (SavedLocationa.ContainsKey(names))
{
sw.WriteLine(SavedLocationa[names]);
}
else
{
sw.WriteLine("Error no entries found");
}
sw.Flush();
Console.WriteLine("Error no entries found");
}
else if (sections.Length == 2)
{
names = sections[0];
location = sections[1];
if (SavedLocationa.ContainsKey(names))
{
SavedLocationa.Remove(names);
}
else
{
SavedLocationa.Add(names, location);
sw.WriteLine("Update Successful");
}
sw.Flush();
}
}
catch (Exception e)
{
Console.WriteLine("Something went wrong");
Console.WriteLine(e.Message);
}
}
}
}
What functionalities are missing in the server portion of the code?

Related

Client Dissconnect or down

I have 2 Application in a visual studio Windows Forms App(.Net Framework 4) The names of my two programs are:
IpServer
IpClient
My problem is that I do not know what to do that when the IpClient Application closes or stops or the IpServer Application shows a message in messagebox.show("Client Is dissconnect")
IpServer Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace IpServer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
TcpListener tcplist;
Socket s;
private void init()
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
tcplist = new TcpListener(ip,5050);
tcplist.Start();
while (true)
{
s = tcplist.AcceptSocket();
Thread t = new Thread(new ThreadStart(replay));
t.IsBackground = true;
t.Start();
}
}
private void replay()
{
Socket sc = s;
NetworkStream ns = new NetworkStream(sc);
StreamReader reader = new StreamReader(ns);
StreamWriter writer = new StreamWriter(ns);
string str = "";
string response = "";
try { str = reader.ReadLine(); }
catch { str = "error"; }
if (str == "register")
{
MessageBox.Show("ok");
}
response = "registeredSucss,";
writer.WriteLine(response);
writer.Flush();
ns.Close();
sc.Close();
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(init));
t.IsBackground = true;
t.Start();
MessageBox.Show("Server run!!");
button1.Enabled = false;
}
and IpClient Code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace IpClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
TcpClient tcp;
NetworkStream ns;
StreamReader reader;
StreamWriter writer;
string str = "";
private void button1_Click(object sender, EventArgs e)
{
try
{
tcp = new TcpClient("127.0.0.1",5050);
tcp.ReceiveBufferSize = 25000;
tcp.NoDelay = true;
ns = tcp.GetStream();
reader = new StreamReader(ns);
writer = new StreamWriter(ns);
writer.WriteLine("register");
writer.Flush();
str = reader.ReadLine();
string[] strsplit = null;
strsplit = str.Split(',');
if (strsplit[0] != "registeredSucss")
{
MessageBox.Show("Not connected");
}
else
{
MessageBox.Show("Your connected");
}
}
catch
{
MessageBox.Show("error");
}
}
I wrote a complete example for you.
You can modify it according to your needs.
Simply connecting the client to the server without sending or receiving messages will not disconnect.
In the server and the client, there is a thread that continuously calls the receive function, and sends a message when the connection is disconnected.
byte[] buffer = new byte[1024 * 1024 * 2];
int length = socket.Receive(buffer);
if (length == 0) {
///Write the desired operation
}
"Disconnect when closing the window" uses the formclosing event:
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
}
This is the control diagram used by the two windows:
IpClient:
IpServe:
This is the code for the two windows:
IpClient:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace IpClient {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
Socket socket;//The socket responsible for the connection
private void ConnectB_Click(object sender, EventArgs e) {
//Determine whether to request a connection repeatedly
try {
Log("Connected " + socket.LocalEndPoint.ToString() + "\nPlease do not request the connection repeatedly");
} catch {
//Determine whether the input is wrong
try {
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Create IP address and port number;
IPAddress ip = IPAddress.Parse(Ipbox.Text);
int port = Convert.ToInt32(PortBox.Text);
IPEndPoint iPEndPoint = new IPEndPoint(ip, port);
//Determine whether you can connect to the server
try {
socket.Connect(iPEndPoint);
Log("Connected " + socket.LocalEndPoint.ToString());
//Start receiving data thread
Thread th = new Thread(receive);
th.IsBackground = true;
th.Start();
} catch {
Log("Port is not open");
}
} catch {
socket = null;
Log("Input error");
}
}
}
private void Log(string str) {
ClientLog.AppendText(str + "\r\n");
}
private void receive() {
while (true) {
//Determine whether the data can be received
try {
byte[] buffer = new byte[1024 * 1024 * 2];
int length = socket.Receive(buffer);
if (length == 0) {
Log("Port is not open");
CloseSocket(socket);
socket = null;
break;
}
string txt = Encoding.UTF8.GetString(buffer, 0, length);
Log(socket.RemoteEndPoint + ":\r\t" + txt);
} catch {
break;
}
}
}
private void Form1_Load(object sender, EventArgs e) {
Control.CheckForIllegalCrossThreadCalls = false;
}
private void CloseB_Click(object sender, EventArgs e) {
if (socket != null) {
CloseSocket(socket);
socket = null;
Log("Connection closed");
} else {
Log("Not connected");
}
}
private void SendB_Click(object sender, EventArgs e) {
try {
string txt = SendText.Text;
byte[] buffer = Encoding.ASCII.GetBytes(txt);//ascii encoding
socket.Send(buffer);
} catch {
Log("Not connected");
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
if (socket != null) {
CloseSocket(socket);
socket = null;
}
}
//Disconnect socket
private void CloseSocket(Socket o) {
try {
o.Shutdown(SocketShutdown.Both);
o.Disconnect(false);
o.Close();
} catch {
Log("error");
}
}
}
}
IpServer:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace IpServer {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
Socket socketSend;//Socket responsible for communication
Socket socketListener;//Socket responsible for monitoring
Dictionary<string, Socket> dictionary = new Dictionary<string, Socket>();//Store the connected Socket
private void listnerB_Click(object sender, EventArgs e) {
//Create a listening socket
//SocketType.Stream streaming corresponds to the tcp protocol
//Dgram, datagram corresponds to UDP protocol
socketListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try {
//Create IP address and port number;
IPAddress ip = IPAddress.Parse(Ipbox.Text);
int port = Convert.ToInt32(PortBox.Text);
IPEndPoint iPEndPoint = new IPEndPoint(ip, port);
//Let the listening socket bind the ip and port number
socketListener.Bind(iPEndPoint);
Log("Listen successfully" + ip + "\t" + port);
//Set up the listening queue
socketListener.Listen(10);//Maximum number of connections at a time
Thread thread = new Thread(Listen);
thread.IsBackground = true;
thread.Start(socketListener);
} catch {
Log("Failed to listen");
}
}
//Use threads to receive data
private void Listen(object o) {
Socket socket = o as Socket;
while (true) {
//The socket responsible for monitoring is used to receive client connections
try {
//Create a socket responsible for communication
socketSend = socket.Accept();
dictionary.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
clientCombo.Items.Add(socketSend.RemoteEndPoint.ToString());
clientCombo.SelectedIndex = clientCombo.Items.IndexOf(socketSend.RemoteEndPoint.ToString());
Log("Connected " + socketSend.RemoteEndPoint.ToString());
//Start a new thread to receive information from the client
Thread th = new Thread(receive);
th.IsBackground = true;
th.Start(socketSend);
} catch {
continue;
}
}
}
//The server receives the message from the client
private void receive(object o) {
Socket socketSend = o as Socket;
while (true) {
//Try to connect to the client
try {
//After the client connects successfully, the server receives the message from the client
byte[] buffer = new byte[1024 * 1024 * 2];//2M大小
//Number of valid bytes received
int length = socketSend.Receive(buffer);
if (length == 0) {
string tmpIp = socketSend.RemoteEndPoint.ToString();
Log(tmpIp + " Offline");
clientCombo.Items.Remove(tmpIp);
//Try to delete the connection information
try {
clientCombo.SelectedIndex = 0;
} catch {
clientCombo.Text = null;
}
CloseSocket(dictionary[tmpIp]);
dictionary.Remove(tmpIp);
break;
}
string str = Encoding.ASCII.GetString(buffer, 0, length);
Log(socketSend.RemoteEndPoint.ToString() + "\n\t" + str);
} catch {
break;
}
}
}
private void Log(string str) {
ServerLog.AppendText(str + "\r\n");
}
private void Form1_Load(object sender, EventArgs e) {
//Cancel errors caused by cross-thread calls
Control.CheckForIllegalCrossThreadCalls = false;
}
//Send a message
private void SendB_Click(object sender, EventArgs e) {
string txt = SendText.Text;
byte[] buffer = Encoding.UTF8.GetBytes(txt);
try {
string ip = clientCombo.SelectedItem.ToString();//Get the selected ip address
Socket socketsend = dictionary[ip];
socketsend.Send(buffer);
} catch{
Log("Transmission failed");
}
}
private void Close_Click(object sender, EventArgs e) {
try {
try {
string tmpip = socketSend.RemoteEndPoint.ToString();
CloseSocket(dictionary[tmpip]);
dictionary.Remove(tmpip);
clientCombo.Items.Remove(tmpip);
try {
clientCombo.SelectedIndex = 0;
} catch {
clientCombo.Text = null;
}
socketSend.Close();
Log(socketSend.RemoteEndPoint.ToString() + "Offline");
socketListener.Close();
Log("Listener is closed");
} catch{
socketListener.Close();
Log("Listener is closed");
}
} catch {
Log("close error");
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
try {
try {
string tmpip = socketSend.RemoteEndPoint.ToString();
CloseSocket(dictionary[tmpip]);
dictionary.Remove(tmpip);
clientCombo.Items.Remove(tmpip);
try {
clientCombo.SelectedIndex = 0;
} catch {
clientCombo.Text = null;
}
socketSend.Close();
socketListener.Close();
} catch {
socketListener.Close();
}
} catch {
}
}
private void CloseSocket(Socket o) {
try {
o.Shutdown(SocketShutdown.Both);
o.Disconnect(false);
o.Close();
} catch {
Log(o.ToString() + "error");
}
}
}
}
OutPut:
Closing the window causes disconnection:
Disconnect manually:
Transfer data:
If you have any question about my code, please add a comment below.

signalr .net client reconnect error

I'm writing a program that makes remote desktop connection with signalr. I keep sending screenshots (in the .net client) for it. But when I reconnect to the server after a while, I get error: Connection started reconnecting before invocation result was received.
public void ImageMain()
{
var querstring = new Dictionary<string, string>();
querstring.Add("userid", "sessionlocal");
var hubConnectionMouse = new HubConnection("http://localhost:8089/", querstring);
Program p = new Program();
IHubProxy myHubProxyMouse = hubConnectionMouse.CreateHubProxy("MyHub");
string a = "";
try
{
hubConnectionMouse.Start().Wait();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
byte[] ekran;
while (true)
{
ekran = null;
ekran = EkranGoruntusu();
if (ekran.Length < 80000)
{
try
{
myHubProxy.Invoke("addMessage", "sessionlocal", ekran).ContinueWith(task =>
{
if (task.IsFaulted)
{
Console.WriteLine("!!! image gönderilirken hata olıştu:{0} \n",
task.Exception.GetBaseException() + "tekrar bağlanılıyor....");
}
else
{
Console.WriteLine("Add messgae" + " gonderilecek ekran boyutu " + ekran.Length);
Console.WriteLine("hub durumu" + hubConnection.State);
}
}).Wait();
}
catch (Exception exception)
{
Console.WriteLine("bağlantı hatas tekrar bağlanılıyor" + exception.Message);
Console.ReadKey();
}
}
else
{
Console.WriteLine("gonderilcek goruntü cok büyük");
}
}
Console.ReadLine();
}

Why Does Threading Break Named Pipes During Inter-Processing Communications?

I am trying to write a sample C# program for named pipe streaming. I create two executable files, one for server and another for client. Please check my code below. These two applications sometimes work correctly and sometimes client application closes without any reason or exception, resulting Pipe is broken exception in server application. I think, in this situation, these processes are not synchronized, specially when I put some delays in their code such as debug mode delays. Why is client process being suddenly closed when server is still waiting for PipeDrain (pipeServer.WaitForPipeDrain())?
I appreciate your help.
Server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Pipes;
using System.IO;
using System.Threading;
namespace NamedPipeServer
{
class NamedPipeServerClass
{
static void Main(string[] args)
{
NamedPipeServerStream pipeServer = new NamedPipeServerStream("namedPipe", PipeDirection.InOut, 4);
StreamReader SR = new StreamReader(pipeServer);
StreamWriter SW = new StreamWriter(pipeServer);
pipeServer.WaitForConnection();
string temp;
try
{
SW.WriteLine("Waiting");
SW.Flush();
pipeServer.WaitForPipeDrain();
temp = SR.ReadLine();
Console.WriteLine(temp + '\n');
SW.WriteLine("Hello");
SW.Flush();
pipeServer.WaitForPipeDrain();
temp = SR.ReadLine();
Console.WriteLine(temp + '\n');
SW.WriteLine("How are you?");
SW.Flush();
pipeServer.WaitForPipeDrain();
temp = SR.ReadLine();
Console.WriteLine(temp + '\n');
SW.WriteLine("GoodBye");
SW.Flush();
pipeServer.WaitForPipeDrain();
temp = SR.ReadLine();
Console.WriteLine(temp + '\n');
}
catch (Exception ex)
{
throw ex;
}
finally
{
pipeServer.WaitForPipeDrain();
if (pipeServer.IsConnected)
{
pipeServer.Disconnect();
}
}
Console.WriteLine("Server: Press any key to exit...");
Console.ReadLine();
}
}
}
Client:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Pipes;
using System.IO;
using System.Threading;
namespace NamedPipeClient
{
class NamedPipeClientClass
{
static NamedPipeClientStream pipeClient;
static StreamReader SR;
static StreamWriter SW;
static Thread Conversation = new Thread(new ThreadStart(Con_function));
static bool HandShake_Ok = false;
static void Main(string[] args)
{
pipeClient = new NamedPipeClientStream(".", "namedPipe", PipeDirection.InOut, PipeOptions.None);
if (pipeClient.IsConnected != true)
{
pipeClient.Connect();
}
SR = new StreamReader(pipeClient);
SW = new StreamWriter(pipeClient);
Conversation.Name = "ConversationThread";
Conversation.IsBackground = true;
Conversation.Start();
}
static void Con_function()
{
string temp;
while (true)
{
try
{
temp = SR.ReadLine();
}
catch (Exception ex)
{
throw ex;
}
if (temp == "Waiting")
{
HandShake_Ok = true;
try
{
SW.WriteLine("Welcome");
SW.Flush();
}
catch (Exception ex)
{
throw ex;
}
}
else if (HandShake_Ok && temp == "Hello")
{
try
{
SW.WriteLine("Hi");
SW.Flush();
}
catch (Exception ex)
{
throw ex;
}
}
else if (HandShake_Ok && temp == "How are you?")
{
try
{
SW.WriteLine("I am fine");
SW.Flush();
}
catch (Exception ex)
{
throw ex;
}
}
else if (HandShake_Ok && temp == "GoodBye")
{
try
{
HandShake_Ok = false;
SW.WriteLine("Good bye :)");
SW.Flush();
}
catch (Exception ex)
{
throw ex;
}
}
}
}
}
}
Update: In the client the writings and readings into pipe are done in a thread, called Conversation. If I remove this thread and bring all writings and readings into Main function, the problem will be resolved. Why does thread have such an effect on inter-process pipeline communications?
I believe what you are experiencing here is since Conversation.IsBackground = true; the client application will NOT wait for the Conversation thread to complete before exiting
Try:
Conversation.Name = "ConversationThread";
Conversation.IsBackground = true;
Conversation.Start();
Conversation.Join();
The Conversation.Join(); blocks the calling thread from executing until the thread object terminates
See Thread.Join Method & Thread.IsBackground Property on MSDN

IRCBot C# connection issues

I am having an issue with my IRC Bot I am trying to write in c# just as a way to help get my head around the IRC protocol, I am planning on writing a client/server in the future but as you can prolly guess I am far off this :P
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
namespace LolBot
{
struct IRCConfig
{
public string server;
public int port;
public string nick;
public string name;
}
class IRCBot
{
TcpClient IRCConnection = null;
IRCConfig config;
NetworkStream ns = null;
StreamReader sr = null;
StreamWriter sw = null;
public IRCBot(IRCConfig config)
{
this.config = config;
try
{
IRCConnection = new TcpClient(config.server, config.port);
}
catch
{
Console.WriteLine("Connection Error");
}
try
{
ns = IRCConnection.GetStream();
sr = new StreamReader(ns);
sw = new StreamWriter(ns);
sendData("USER", config.nick + config.name);
sendData("NICK", config.nick);
}
catch
{
Console.WriteLine("Communication error");
}
finally
{
if (sr != null)
sr.Close();
if (sw != null)
sw.Close();
if (ns != null)
ns.Close();
if (IRCConnection != null)
IRCConnection.Close();
}
}
public void sendData(string cmd, string param)
{
if (param == null)
{
sw.WriteLine(cmd);
sw.Flush();
Console.WriteLine(cmd);
}
else
{
sw.WriteLine(cmd + " " + param);
sw.Flush();
Console.WriteLine(cmd + " " + param);
}
}
public void IRCWork()
{
string[] ex;
string data;
bool shouldRun = true;
while (shouldRun)
{
data = sr.ReadLine();
Console.WriteLine(data);
char[] charSeparator = new char[] { ' ' };
ex = data.Split(charSeparator, 5);
if (ex[0] == "PING")
{
sendData("PONG", ex[1]);
}
if (ex.Length > 4) //is the command received long enough to be a bot command?
{
string command = ex[3]; //grab the command sent
switch (command)
{
case ":!join":
sendData("JOIN", ex[4]); //if the command is !join send the "JOIN" command to the server with the parameters set by the user
break;
case ":!say":
sendData("PRIVMSG", ex[2] + " " + ex[4]); //if the command is !say, send a message to the chan (ex[2]) followed by the actual message (ex[4]).
break;
case ":!quit":
sendData("QUIT", ex[4]); //if the command is quit, send the QUIT command to the server with a quit message
shouldRun = false; //turn shouldRun to false - the server will stop sending us data so trying to read it will not work and result in an error. This stops the loop from running and we will close off the connections properly
break;
}
}
}
}
}
class Program
{
static void Main(string[] args)
{
IRCConfig conf = new IRCConfig();
conf.name = "LolBot";
conf.nick = "LolBot";
conf.port = 6667;
conf.server = "irc.strictfp.com";
new IRCBot(conf);
Console.WriteLine("Bot quit/crashed");
Console.ReadLine();
}
}
}
Whenever I execute the Bot, it comes up with:
USER AspiBot google.com google.com :AspiBot
NICK AspiBot
Bot quit/crashed
I don't really understand why it is quiting before connecting to the server and I am also looking on how to set it up to join a channel, I am aware that I need to use JOIN but I'm not sure how to implent it.
You should probably not do so much in the constructor, but the problem you are encountering here is that you are not calling IRCWork() after newing up the bot.
var bot = new IRCBot(conf);
bot.IRCWork();
EDIT You are also closing all of your connections in the finally block of your constructor, so IRCWork() isn't going to work anyway. Try implementing IDisposable, and putting your close logic in Dispose():
using (var bot = new IRCBot(conf))
{
bot.IRCWork();
}
Quick refactor of posted code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
namespace LolBot
{
internal struct IRCConfig
{
public string server;
public int port;
public string nick;
public string name;
}
internal class IRCBot : IDisposable
{
private TcpClient IRCConnection = null;
private IRCConfig config;
private NetworkStream ns = null;
private StreamReader sr = null;
private StreamWriter sw = null;
public IRCBot(IRCConfig config)
{
this.config = config;
}
public void Connect()
{
try
{
IRCConnection = new TcpClient(config.server, config.port);
}
catch
{
Console.WriteLine("Connection Error");
throw;
}
try
{
ns = IRCConnection.GetStream();
sr = new StreamReader(ns);
sw = new StreamWriter(ns);
sendData("USER", config.nick + config.name);
sendData("NICK", config.nick);
}
catch
{
Console.WriteLine("Communication error");
throw;
}
}
public void sendData(string cmd, string param)
{
if (param == null)
{
sw.WriteLine(cmd);
sw.Flush();
Console.WriteLine(cmd);
}
else
{
sw.WriteLine(cmd + " " + param);
sw.Flush();
Console.WriteLine(cmd + " " + param);
}
}
public void IRCWork()
{
string[] ex;
string data;
bool shouldRun = true;
while (shouldRun)
{
data = sr.ReadLine();
Console.WriteLine(data);
char[] charSeparator = new char[] {' '};
ex = data.Split(charSeparator, 5);
if (ex[0] == "PING")
{
sendData("PONG", ex[1]);
}
if (ex.Length > 4) //is the command received long enough to be a bot command?
{
string command = ex[3]; //grab the command sent
switch (command)
{
case ":!join":
sendData("JOIN", ex[4]);
//if the command is !join send the "JOIN" command to the server with the parameters set by the user
break;
case ":!say":
sendData("PRIVMSG", ex[2] + " " + ex[4]);
//if the command is !say, send a message to the chan (ex[2]) followed by the actual message (ex[4]).
break;
case ":!quit":
sendData("QUIT", ex[4]);
//if the command is quit, send the QUIT command to the server with a quit message
shouldRun = false;
//turn shouldRun to false - the server will stop sending us data so trying to read it will not work and result in an error. This stops the loop from running and we will close off the connections properly
break;
}
}
}
}
public void Dispose()
{
if (sr != null)
sr.Close();
if (sw != null)
sw.Close();
if (ns != null)
ns.Close();
if (IRCConnection != null)
IRCConnection.Close();
}
}
internal class Program
{
private static void Main(string[] args)
{
IRCConfig conf = new IRCConfig();
conf.name = "LolBot";
conf.nick = "LolBot";
conf.port = 6667;
conf.server = "irc.strictfp.com";
using (var bot = new IRCBot(conf))
{
bot.Connect();
bot.IRCWork();
}
Console.WriteLine("Bot quit/crashed");
Console.ReadLine();
}
}
}

Socket accepts Multiple Clients, but i'm unable able to open the file

Basically I've written this program to check for strings. I've used socket method for this.
The problem is, I am unable to figure out how and where exactly to open the file in this program and search for the strings. Instead of giving the search string in the program, I want the client to be able to type/search for any strings they want. And when I run the program, I need the output on client's screen.
How can I improve this program? Could someone please help me out with the code?
This is my program :
class Program
{
static void Main(string[] args)
{
TcpListener serversocket = new TcpListener(8888);
TcpClient clientsocket = default(TcpClient);
serversocket.Start();
Console.WriteLine(">> Server Started");
while (true)
{
clientsocket = serversocket.AcceptTcpClient();
Console.WriteLine("Accept Connection From Client");
LineMatcher lm = new LineMatcher(clientsocket);
Thread thread = new Thread(new ThreadStart(lm.Run));
thread.Start();
Console.WriteLine("Client connected");
}
Console.WriteLine(" >> exit");
Console.ReadLine();
clientsocket.Close();
serversocket.Stop();
}
}
public class LineMatcher
{
private static Regex _regex = new Regex("not|http|console|application", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
private TcpClient _client;
public LineMatcher(TcpClient client)
{
_client = client;
}
public void Run()
{
try
{
using (var reader = new StreamReader(_client.GetStream()))
{
string line;
int lineNumber = 0;
while (null != (line = reader.ReadLine()))
{
lineNumber += 1;
foreach (Match match in _regex.Matches(line))
{
Console.WriteLine("Line {0} matches {1}", lineNumber, match.Value);
}
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
}
Console.WriteLine("Closing client");
_client.Close();
}
}
Here is a simple demo client that works for me:
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
namespace AClient
{
class Client
{
static void Main()
{
using (var client = new TcpClient("localhost", 8888))
{
Console.WriteLine(">> Client Started");
using (var r = new StreamReader(#"E:\input.txt", Encoding.UTF8))
using (var w = new StreamWriter(client.GetStream(), Encoding.UTF8))
{
string line;
while (null != (line = r.ReadLine()))
{
w.WriteLine(line);
w.Flush(); // probably not necessary, but I'm too lazy to find the docs
}
}
Console.WriteLine(">> Goodbye");
}
}
}
}

Categories