What Im actualy trying to do is to create a windows service, that will be listening to one exact IP adress and port and after receiving message write information to the file.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Threading;
using System.Net;
using System.IO;
namespace Active_service
{
public partial class Service1 : ServiceBase
{
const int port = 8005;
static TcpListener listener;
public Service1()
{
InitializeComponent();
this.CanStop = true;
this.CanPauseAndContinue = true;
this.AutoLog = true;
File.AppendAllText("Log.txt","\n Initialized" + " " + DateTime.Now.ToString());
}
protected override void OnStart(string[] args)
{
File.AppendAllText("Log.txt","\n Started!");
Thread listen_thread = new Thread(new ThreadStart(Listen));
listen_thread.Start();
}
public void Listen()
{
IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"),port);
Socket listen_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
listen_socket.Bind(ipPoint);
listen_socket.Listen(10);
File.AppendAllText("Log.txt", "\n Listening!");
while (true)
{
Socket handler = listen_socket.Accept();
StringBuilder builder = new StringBuilder();
int bytes = 0;
byte[] data = new byte[256];
do
{
bytes = handler.Receive(data);
builder.Append(Encoding.Unicode.GetString(data, 0, bytes));
}
while (handler.Available > 0);
File.AppendAllText("Log.txt","\n Message received:" + builder.ToString());
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception ex)
{
File.AppendAllText("Log.txt","\n " + ex.Message);
}
}
protected override void OnStop()
{
File.AppendAllText("Log.txt", "Stopped!");
}
protected override void OnPause()
{
base.OnPause();
}
protected override void OnContinue()
{
base.OnContinue();
}
}
}
The problem is: When I'm compiling code, line "\n Initialized!" is added to the file, but after I'm setting up the service it's accepting TPC communication (no error throwed after I'm sending message from other software), but nothing is added to "Log.txt", even "Initialized" message.
What I'm doing wrong?
Related
I am attempting to design a windows service that contains a web server to do basic get request handling. Requests from the localhost work just find but I am unable to process requests from other machines. On python, setting the IP address to 0.0.0.0 allows the server to process requests from any IP on the network. I have found examples that use http://*:port/ or http://+:port/ to obtain this functionality in C# but these have not worked for me.
I am currently starting a HttpListener (WebServer.cs) when the windows service (UsherService.cs) receives its start command. If there is a better way to do this, I'd appreciate that answer as well.
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace UsherService
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new UsherService()
};
ServiceBase.Run(ServicesToRun);
}
}
}
UsherService.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace UsherService
{
public partial class UsherService : ServiceBase
{
WebServer ws;
public UsherService()
{
InitializeComponent();
}
public static string SendResponse(HttpListenerRequest request)
{
return string.Format("<HTML><BODY>My web page.<br>{0}</BODY></HTML>", DateTime.Now);
}
protected override void OnStart(string[] args)
{
try
{
ws = new WebServer(SendResponse, "http://*:5000/");
ws.Run();
System.IO.File.AppendAllText(#"C:\Users\kburd\Desktop\WriteText.txt", "Started Successfully");
}
catch(Exception e)
{
System.IO.File.AppendAllText(#"C:\Users\kburd\Desktop\WriteText.txt", e.Message);
}
}
protected override void OnStop()
{
System.IO.File.AppendAllText(#"C:\Users\kburd\Desktop\WriteText.txt", "Stopped Successfully");
}
}
}
WebServer.cs
using System;
using System.Net;
using System.Text;
using System.Threading;
public class WebServer
{
private readonly HttpListener _listener = new HttpListener();
private readonly Func<HttpListenerRequest, string> _responderMethod;
public WebServer(string[] prefixes, Func<HttpListenerRequest, string> method)
{
if (!HttpListener.IsSupported)
throw new NotSupportedException(
"Needs Windows XP SP2, Server 2003 or later.");
// URI prefixes are required
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
// A responder method is required
if (method == null)
throw new ArgumentException("method");
foreach (string s in prefixes)
{
_listener.Prefixes.Add(s);
System.IO.File.AppendAllText(#"C:\Users\kburd\Desktop\WriteText2.txt", s);
}
_responderMethod = method;
_listener.Start();
}
public WebServer(Func<HttpListenerRequest, string> method, params string[] prefixes)
: this(prefixes, method) { }
public void Run()
{
ThreadPool.QueueUserWorkItem((o) =>
{
Console.WriteLine("Webserver running...");
try
{
while (_listener.IsListening)
{
ThreadPool.QueueUserWorkItem((c) =>
{
var ctx = c as HttpListenerContext;
try
{
string rstr = _responderMethod(ctx.Request);
byte[] buf = Encoding.UTF8.GetBytes(rstr);
ctx.Response.ContentLength64 = buf.Length;
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
}
catch { } // suppress any exceptions
finally
{
// always close the stream
ctx.Response.OutputStream.Close();
}
}, _listener.GetContext());
}
}
catch { } // suppress any exceptions
});
}
public void Stop()
{
_listener.Stop();
_listener.Close();
}
}
The firewall was blocking the localhost from communicating to other devices on the network. I had to allow for communication over that port
I am attempting to connect multiple clients to a server and monitor their connection...
I am trying to get a better understanding of TcpListener and TcpClient while creating these programs.
I found my server code from another stackoverflow answer as I am looking to get a connection from multiple clients, I have edited it abit:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace socket_server
{
class connect
{
public class State
{
public Socket workSocket = null;
public const int bufferSize = 1024;
public byte[] buffer = new byte[bufferSize];
public StringBuilder sb = new StringBuilder();
}
public class Server
{
public static ManualResetEvent allDone = new ManualResetEvent(false);
private static IPEndPoint findMe()
{
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 5505);
return localEndPoint;
}
public static void start()
{
try
{
TcpListener listener = new TcpListener(findMe());
TcpClient client;
listener.Start();
Console.WriteLine("Server IP: {0}\n", findMe());
Console.WriteLine("Waiting for Connection...");
while (true)
{
client = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(threadProc, client);
}
Console.ReadKey();
} catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void threadProc(object obj)
{
try
{
var client = (TcpClient)obj;
} catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
}
You call this like connect.Server.start()
This is my current client code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace socket_client
{
class connect
{
public class State
{
public Socket workSocket = null;
public const int bufferSize = 256;
public byte[] buffer = new byte[bufferSize];
public StringBuilder sb = new StringBuilder();
}
public class Client
{
private const int port = 5505;
private static String response = String.Empty;
private static IPEndPoint findServer()
{
IPHostEntry ipHostInfo = Dns.Resolve("10.1.2.30");
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
return remoteEP;
}
public static void start()
{
TcpClient client = new TcpClient();
Console.WriteLine("Server IP: {0}", findServer().ToString());
Console.WriteLine("Client IP: {0}\n", software.getIPAddress());
connect(client);
if (client.Connected)
Console.WriteLine("\nConnected to: {0}\n", findServer().ToString());
}
private static void connect(TcpClient client)
{
try
{
client.Connect(findServer());
} catch(Exception e)
{
Console.WriteLine("Attempting to connect to: {0}", findServer().ToString());
connect(client);
}
}
}
}
}
You call this like connect.Client.start();
My classes such as hardware and software simply just get system information.
I would like to know how to check if a connection is dropped and respond with a Console.WriteLine for both Client and Server.
Edit-
This is what I have working for checking to see if a client drops from the server:
...
private static void threadProc(object obj)
{
try
{
var client = (TcpClient)obj;
Byte[] bytes = new Byte[256];
string data = null;
try {
NetworkStream stream = client.GetStream();
int i;
while((i = stream.Read(bytes,0,bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine(">{0}: {1}", ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString(), data);
}
} catch(Exception e)
{
Console.WriteLine(">>{0} Lost Connection...", ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString());
}
} catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
...
You will only be able to detect if a connection was closed when reading on the stream fails, since there is no event which would notify you.
You might raise your own event in the connection-handling class.
But for some reasons, it is possible, that a TCP-Connection drops without a pending Read()-call to fail.
So, there is no perfect method, like handling an event, which always notifies you, when the connection broke. So you have to implement some keep-alive mechanism. E.g. send a ping/pong every once in a while and wait for the answer. If there is no answer in a defined time, you can close the connection.
I got this error while compiling. what does it mean and how do i resolve it?
'System.Net.Sockets.Socket.Dispose(bool)' is inaccessible due to its protection level
Here are both of my files;
Listener.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Multi_con_Server
{
class Listener
{
Socket s;
public bool Listening
{
get;
private set;
}
public int Port
{
get;
private set;
}
public Listener(int port)
{
Port = port;
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void Start()
{
if (Listening)
return;
s.Bind(new IPEndPoint(0, Port));
s.Listen(0);
s.BeginAccept(callback, null);
Listening = true;
}
public void Stop()
{
if (!Listening)
return;
s.Close();
s.Dispose();
s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
void callback(IAsyncResult ar)
{
try
{
Socket s = this.s.EndAccept(ar);
if (SocketAccepted != null)
{
SocketAccepted(s);
}
this.s.BeginAccept(callback, null);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public delegate void SocketAccecptedHandler(Socket e);
public event SocketAccecptedHandler SocketAccepted;
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Multi_Con_C
{
class Program
{
static void Main(string[] args)
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
s.Connect("127.0.0.1", 8);
s.Close();
s.Dispose();
}
}
}
From MSDN, Socket.Close() automatically "releases all associated resources". You can safely remove all occurances of Socket.Dispose() from your code.
Why I can't recieved messages from Chat Server ?
I developed Chat Client in Visual Studio C# with mono for android.
I want to receive mesagens from Chat server they are sent but he Chat Client may be receiving them and i can not seem to show in Text1.Text
The Source Code Chat Client for receiving messages:
//Criado por EcoDuty, Frederico Vaz
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
//
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Runtime.InteropServices;
namespace ChatClient_Android
{
[Activity(Label = "ChatClient_Android", MainLauncher = true, Icon = "#drawable/icon")]
public class MainChat : Activity
{
public delegate void OnRecievedMessage(string message);
public MainChat form;
const int WM_VSCROLL = 0x115;
const int SB_BOTTOM = 7;
TextView text1;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button ligar = FindViewById<Button>(Resource.Id.btligar);
text1 = FindViewById<TextView>(Resource.Id.text1);
//Conexão com o servidor
ligar.Click += delegate
{
Connect();
ligar.Enabled = false;
};
}
//Função Actualizar a Caixa de Entrada de Mensagens
private void UpdateTextbox(string text)
{
text1.Text += "\r\n";
text1.Text += text;
}
//Recieved Mesages
public void RecievedMessage(string message)
{
UpdateTextbox(message);
}
//TCP Connection
public StreamWriter Outgoing;
private StreamReader Incoming;
private TcpClient Connection;
private Thread Messages;
private IPAddress IP;
//public string host;
//public string nick;
//MainChat m_ParentForm;
bool isConnected;
//Função Conectar
public void Connect()
{
try
{
IP = IPAddress.Parse("10.0.2.2");
Connection = new TcpClient();
Connection.Connect(IP, 1986);
Outgoing = new StreamWriter(Connection.GetStream());
Outgoing.WriteLine("EcoDuty");
Outgoing.Flush();
//m_ParentForm.Vis(true);
Messages = new Thread(new ThreadStart(this.Communication));
Messages.Start();
}
catch (Exception e) { Disconnected(e.Message); }
}
private void Communication()
{
Incoming = new StreamReader(Connection.GetStream());
string check = Incoming.ReadLine();
if (check[0] == '1')
{
//Vis(true);
isConnected = true;
}
else
{
string Reason = "Disconnected: ";
Reason += check.Substring(2, check.Length - 2);
Disconnected(Reason);
return;
}
while (isConnected == true)
{
try
{
ServerMessage(Incoming.ReadLine());
}
catch (Exception e)
{
if (isConnected == true)
{
Disconnected("Connection to server lost");
Console.WriteLine("Connection Lost: " + e.ToString());
}
break;
}
}
}
private void ServerMessage(string message)
{
try
{
RecievedMessage(message);
}
catch { }
}
public void CloseConnection()
{
isConnected = false;
Incoming.Close();
Outgoing.Close();
Connection.Close();
Messages.Abort();
}
public void SendMessage(string message)
{
Outgoing.WriteLine(message);
Outgoing.Flush();
}
}
}
You seem to be trying to update the text from a non UI thread (if you follow the calls stack you see that the method is triggered from a dedicated thread you spawn):
private void UpdateTextbox(string text)
{
text1.Text += "\r\n";
text1.Text += text;
}
Instead use RunOnUiThread() to schedule the text change to run on the UI thread:
private void UpdateTextbox(string text)
{
RunOnUiThread(() =>
{
text1.Text += "\r\n";
text1.Text += text;
});
}
Also you should get rid of the empty exception catching you do along the way - this most likely masked the problem.
Also always check the catlog for exceptions they usually are a good indicator.
Ok, simple problem hopefully.
I have started to make a simple server for a simple MORPG game im making, the client connected, and then disconnects, simple, the server catches the new client, but doesn't catch when it disconnects, whats wrong?
Im hoping its something stupidly obvious.
Here's my server 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.Sockets;
using System.IO;
using System.Threading;
namespace ChaWilPeiBle
{
public partial class MainForm : Form
{
public bool ServerON = false;
public TcpListener ServerL;
public int ServerLoad = 2;
public string ServerINFtxt = "";
public ASCIIEncoding AE = new ASCIIEncoding();
public MainForm()
{
InitializeComponent();
}
private void LBL_SS_Click(object sender, EventArgs e)
{
}
private void MainForm_Load(object sender, EventArgs e)
{
LBL_SS.ForeColor = Color.Red;
}
public void AddH(string S)
{
ServerINFtxt += S;
}
public void Server()
{
try
{
ServerL = new TcpListener(47);
ServerL.Start();
AddH("\nServer Started On Port 47");
}
catch(Exception e)
{
MessageBox.Show("Error starting Server.__________________\n"+e.ToString());
}
while (true)
{
TcpClient TCPC;
TCPC = ServerL.AcceptTcpClient();
if (ServerLoad < 100)
{
Thread T = new Thread(HandleClient);
T.Start((object)TCPC);
}
else
{
byte[] BYTES = AE.GetBytes("NoAccess:Full");
NetworkStream NS = TCPC.GetStream();
NS.Write(BYTES, 0, BYTES.Length);
}
}
}
public void HandleClient(object C)
{
ServerLoad++;
TcpClient Client = (TcpClient)C;
NetworkStream NS = Client.GetStream();
AddH("Client Connected.\nServer Load: " + ServerLoad);
Thread T = new Thread(ReadClient);
T.Start(C);
try
{
while (true) { NS.Write(AE.GetBytes(""), 0, AE.GetBytes("").Length); }
}
catch { }
ServerLoad--;
AddH("Client Disconnected.\nServer Load: " + ServerLoad);
}
public void ReadClient(object C)
{
//TcpClient Client = (TcpClient)C;
}
private void startStopToolStripMenuItem_Click(object sender, EventArgs e)
{
LBL_SS.Text = "Server On";
LBL_SS.ForeColor = Color.Green;
if (ServerON == false)
{
Thread T = new Thread(Server);
T.Start();
}
ServerON = true;
}
private void Update_Tick(object sender, EventArgs e)
{
ServerINF.Text = ServerINFtxt;
PB_SL.Value = ServerLoad;
}
}
}
If you make a blocking call to read on a network stream and it returns 0 bytes as the length that it read it means that your client has disconnected. You will not get an exception until you try write to this connection. That's my best guess as to what is happening.