TCPListner, Winsock Check whether any client socket available to connect? - c#

We have web application , it works as Socket Listner. I wanted to check before the AcceptSocket , whether there is any Client Socket available to connect to this listner. I want to display a message if there is no Client Socket to connect and cancel send/receive of data.
I am using TCPListner using ASP.net C# for the web application. The Client socket is windows VB6 application using Winsock control.
Socketing programme, ASP.Net C#, VS2008
Thanks you for the reply ,
see below my sample code for communicate with server
clsCommunication.cs, this class file imports into .aspx page. I tried using Console.WriteLine(), but cann't shown this message.
I wanted to display alert box , so that user understands there is no connection OR display on status bar or highlight a frame/box etc.
public void Communicationcation()
{
byte[] bytes = new byte[1024];
string strSiteID = "SiteID";
socket.Start();
if (!socket.Pending())
{
Console.WriteLine("Sorry, no connection requests have arrived");
}
else
{
client = socket.AcceptSocket();
if (client.Connected == true)
{
decimal dSiteID = decimal.Parse(GetSiteSetting(ref strSiteID).ToString());
IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
WriteLog(string.Format("Connected with {0} at port {1}", clientep.Address, clientep.Port));
string strWelcome = STARTMESSAGE + "WHOAMI" + " " + dSiteID + " " + dSiteID + FINISHMESSAGE;
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(strWelcome);
int i = client.Send(data, data.Length, SocketFlags.None);
WriteLog(String.Format("Message sent {0} bytes!", i));
//Get reply from the Connected cleint.
i = client.Receive(bytes, bytes.Length, SocketFlags.None);
if (i != -1)
{
WriteLog(string.Format(System.Text.Encoding.UTF8.GetString(bytes)));
}
}
}
}

You can use TcpListener's Pending method, see http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.pending.aspx

Related

Why is Ruby sockets server working with other Ruby sockets client but not a C# sockets client?

So I have two Ruby programs, they are a client and server sockets programs and they work together exchanging messages. But a C# client does not work. I give MCVE, first the ruby client.
#socketClient.rb
#With thanks to https://code.likeagirl.io/socket-programming-in-ruby-f714131336fd
require "socket"
while sum = $stdin.gets.chomp # Read lines from the socket
socket = TCPSocket.open("localhost", 3000)
#puts "Starting the Client..................."
socket.puts sum
while message = socket.gets # Read lines from the socket
puts message.chomp
end
socket.close # Close the socket
end
#puts "Closing the Client..................."
and the server
#simplestSocketServer.rb
#With thanks to https://code.likeagirl.io/socket-programming-in-ruby-f714131336fd
require "socket"
port = 3000
ipAddress = "127.0.0.1"
server = TCPServer.open(ipAddress, port) # Server would listen on port 3000
loop { # Servers run forever
puts "Starting the Server, accepting connections on port " + port.to_s + "..................."
client_connection = server.accept # Establish client connect connection
begin
clientText = client_connection.gets.chomp
puts clientText
resp = "Acknowledged"
client_connection.puts("#{clientText}" + "#{resp}") # Send the answer to the client
client_connection.puts("Closing the connection with #{client_connection}")
rescue Exception => getException
puts "#{getException}"
end
client_connection.close # Disconnect from the client
}
and the C# console program
using System;
using System.Net.Sockets;
using System.Text;
namespace SimplestCSharpRubySocketsClient
{
class Program
{
static void Main(string[] args)
{
try
{
string ipAddress = "127.0.0.1";
Int16 portNumber = 3000;
TcpClient _client; _client = new TcpClient();
_client.Connect(ipAddress, portNumber);
System.Console.WriteLine("we have connected, seemingly ...");
NetworkStream stream;
stream = _client.GetStream();
Byte[] sendBytes = Encoding.UTF8.GetBytes("some text");
System.Console.WriteLine("writing and flushing some bytes ...");
stream.Write(sendBytes, 0, sendBytes.Length);
stream.Flush();
Byte[] recvBytes = new byte[_client.ReceiveBufferSize];
System.Console.WriteLine("_client.ReceiveBufferSize = " + _client.ReceiveBufferSize); // <--- this prints 65536
System.Console.WriteLine("waiting to read bytes ...");
stream.Read(recvBytes, 0, recvBytes.Length); //<--- hangs here
System.Console.WriteLine("comething came back ...");
string result = Encoding.UTF8.GetString(recvBytes);
string result2 = result.Substring(0, result.LastIndexOf("\r\n"));
_client.Close();
_client.Dispose();
_client = null;
}
catch (Exception ex)
{
//TODO figure out a better error handler
throw ex;
}
}
}
}
The C# program connects and writes bytes but when looking to read bytes it just hangs.
And be aware I am running the C# console program in Visual Studio with admin rights. The two ruby programs run in their own separate Windows console windows.
Folding in some feedback, I added another line in the ruby server to output the clientText. And it prints nothing, suggesting the server is not fully receiving the bytes. Is there a termination signal that C# is required to send?
Thanks in advance.
The problem here is that the C# client does not send a newline at the end of the string, like the Ruby version does (socket.puts sends a string with a newline at the end).
If you change your sendBytes array to include a \n in the payload like this:
Byte[] sendBytes = Encoding.UTF8.GetBytes("some text\n");
you will see that it prints comething came back ... on the console.
The newline is required because of the following gets in the Ruby server:
clientText = client_connection.gets.chomp

Incomplete data received across network from C# to Arduino

I am trying to send a word over to an Arduino running as a server, from a WPF C# application. Every now and again the complete work is not sent.
C# Code
public void send(String message)
{
TcpClient tcpclnt = new TcpClient();
ConState.Content = "Connecting.....";
try
{
tcpclnt.Connect("192.168.0.177", 23);
ConState.Content = "Connected";
String str = message;
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
stm.Write(ba, 0, ba.Length);
tcpclnt.Close();
}
catch (Exception)
{
ConState.Content = "Not Connected";
return;
}
}
How it is sent to the method:
String mes = "back;";
send(mes);
Arduino code:
if (client.available() > 0) {
// Read the bytes incoming from the client:
char thisChar = client.read();
if (thisChar == ';')
{
//Add a space
Serial.println("");
}
else {
//Print because it's not a space
Serial.write(thisChar);
}
}
The Arduino is using the chat server example. I am sending "back;" and "forward;" across. The results on the serial monitor:
back
forwaback
forward
back
forwaforwar
The problem seems to be with this code:
if (client.available() > 0) {
// read the bytes incoming from the client:
char thisChar = client.read();
...
}
What it does is:
Check if we have received data from the client
Read a single byte from the client buffer
Exit, and go on to do other things
As the OP pointed out, this comes direct from Arduino chat server example. In that example, this working correctly in loop() depends on the alreadyConnected flag being set right after a new connection is made: if it isn't, then the buffer is flushed before any data is read. That's one possible landmine.
Nonetheless, there is no reason to change the if block to be a while loop in the OP's case so, in other words instead of
if (client.available() > 0) {
have
while (client.available() > 0) {
The only reason to have an if statement there is to make sure that you frequently do other processing in loop() if you have clients that send a lot of data: If the reading of client data is done from inside a while this loop will not exit until the there is no more data from the client. Since this doesn't seem to be an issue in the asked-about case, the if to while change makes sense.

How to Push data from C# to ZeroMQ and Pull from Node.JS or vice-versa?

Scenario:
I am trying to send a data (say String type) from C# сonsole application to Node.JS server through ZeroMQ.
Information:
Using clrzmq for c# and ZeroMQ libs for C# and Node.JS respectively
I am able to perform push-pull from Node.JS, also push - pull from C#.
So, one thing is confirmed that ZeroMQ - The Intelligent Transport Layer is installed on the machine (Windows 7 64-bit)
Issue:
I am not able to push data from C# Console app to Node.JS app (even tried vice-versa), both are on the same machine and on the same address i.e tcp://127.0.0.1:2222
Node.js code:
var zmq = require('zeromq.node');
var pull_socket = zmq.socket('pull');
pull_socket.connect('tcp://127.0.0.1:2222');
pull_socket.on('message', function (data) {
console.log('received data:\n');
console.log(data);
});
C# code:
namespace DataServiceEngine
{
class Program
{
static void Main(string[] args)
{
//clsApp App = new clsApp();
//App.appId = "001";
//App.name = "Back Office";
//Console.WriteLine("appId :" + App.appId + "\n");
//Console.WriteLine("name:" + App.name + "\n");
try
{
// ZMQ Context and client socket
using (var context = new Context(1))
{
using (Socket client = context.Socket(SocketType.PUSH))
{
client.Connect("tcp://127.0.0.1:2222");
string request = "Hello";
for (int requestNum = 0; requestNum < 10; requestNum++)
{
Console.WriteLine("Sending request {0}...", requestNum);
client.Send(request, Encoding.Unicode);
string reply = client.Recv(Encoding.Unicode);
Console.WriteLine("Received reply {0}: {1}", requestNum, reply);
}
}
}
}
catch (ZMQ.Exception exp)
{
Console.WriteLine(exp.Message);
}
}
}
}
Question: Can anyone tell me what may be the reason or where am I doing wrong?
I had the same issue (but I issued a communication Node.JS -> Node.JS). To solve the problem I used to do sendersocket.connect("tcp://"+host+":"+port); at the sender and receiversocket.bindSync("tcp://*:"+port); at the receiver.
Hope this fix your problem.

block ip by hwid from a text file

I'm working o a project that monitors the IP and HWID on a specific port by TCPListen sent from a client that kills a specific process.
Monitor works perfect, I receive ip and hwid and manage to save to .txt files but what I want to do is to implement a method in server how to block the ip by reading the hwid from a text file.
If some one can help me please I will appreciate it really.
Here is a part from code of client(send) , server (receive):
Server:
textFromClient = ("From: " + tcpClient.Client.RemoteEndPoint + " HWID:" + encoder.GetString(message, 0, bytesRead));
Client:
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(getUniqueID("C"));
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
I think I understand but maybe that I didn't explain right. Well, my server listen on any ip on port 8000 . Clients connects automaticly to server ip and port: exemple : 127.0.0.1:8000. Well clients works like this: When client is connected to server it runs a application".exe". Client is made to kill the process of some application by name. I made a timer for kill the process all the time client is running. When a process is killed client sends to server the IP from pc where process was killed and HWID code: byte[] outStream = System.Text.Encoding.ASCII.GetBytes(getUniqueID("C"));
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush(); and server recive on a listbox the ip and hwid. Well i'm thinking to do so . Example: On this recive message code where i get the HWID from client encoder.GetString(message, 0, bytesRead) to do something like:
if (encoder.GetString(message, 0, bytesRead) = LoadBlockHWID(new FileInfo(#"c:\testfileHWID.txt")));
{
//Code to block connection from specified IP on hwid.
}
I whant that server should not let the client connect to server by HWID. I think I must edit server to see ip and hwid connected and client to send hwid when connected.
Load your HWID into a List/Dictionary by reading your file before you start accepting connections.
in your code where you get tcpClient.Client.RemoteEndPoint, extract just the IPAddress out of that.
Then compare the IPAddress to the block list and if it matches, then see if the HWID matches if that matches then don't perform the task otherwise just do it.
mBlockCheck = new SO15147104();
Here is an example for you. Just instantiate the class and in your line where you Might want to block a request, just
if (!mBlockCheck.BlockRequest(ip, hwid))
{
//Do the operation
}
This is the class code you should be able to figure out from this.
using System.Collections.Generic;
using System.IO;
using System.Net;
public class SO15147104
{
private List<string> HWIDLookup;
private List<IPAddress> IPAddressLookup;
public SO15147104()
{
HWIDLookup = LoadBlockHWID(new FileInfo(#"c:\testfileHWID.txt"));
IPAddressLookup = LoadBlockIPAddresses(new FileInfo(
#"c:\testfileIPAddresses.txt"));
}
public bool BlockRequest(IPAddress ip, string HWIDtoCheck)
{
if (IPAddressLookup.Contains(ip) &&
HWIDLookup.Contains(HWIDtoCheck.ToUpperInvariant().Trim()))
{
return true;
}
return false;
}
private List<IPAddress> LoadBlockIPAddresses(FileInfo fi)
{
List<IPAddress> result = new List<IPAddress>();
using (StreamReader sr = fi.OpenText())
{
while (!sr.EndOfStream)
{
IPAddress theIP = IPAddress.Any;
string thisLine = sr.ReadLine().Trim();
//This should allow IPv6 and IPv4 to be listed 1IP per Line
if (IPAddress.TryParse(thisLine, out theIP))
{
result.Add(theIP);
}
}
}
return result;
}
private List<string> LoadBlockHWID(FileInfo fi)
{
List<string> result = new List<string>();
using (StreamReader sr = fi.OpenText())
{
while (!sr.EndOfStream)
{
result.Add(sr.ReadLine().Trim().ToUpperInvariant());
}
}
return result;
}

Why Packet sending send no data (handshake with minecraft server)?

I am trying to make a Minecraft fake client a.k.a Minecraft chatbot in c# using packets.
I already tried lots of different ways to acomplish this but no luck.
Everytime I send a packet it sends no data (Using a packetsniffer).
Although the packetsniffers says that the total size of the packet is: 190 bytes.
and the size is: 17 bytes.
Here is my code:
static TcpClient client = new TcpClient();
static void Main(string[] args)
{
Console.WriteLine("Start GATHERING INFO.....");
Console.Write("Write a ip: ");
IPAddress ip = IPAddress.Parse("192.168.178.11");
try
{
ip = IPAddress.Parse(Console.ReadLine());
}
catch
{
Console.Write("\nUnknown/Wrong ip entered redirecting to : 127.0.0.1 (AKA Localhost)");
ip = IPAddress.Parse("192.168.178.11");
}
Console.Write("\nWrite a port: ");
int port = int.Parse(Console.ReadLine());
Console.WriteLine("Connecting.....");
try
{
client.Connect(ip, port);
client.NoDelay = false;
Console.WriteLine("Connection succesfull!");
}catch
{
Console.WriteLine("--== ERROR WHILE TRYING TO CONNECT PLEASE RESTART PROGRAM ==--");
Console.ReadKey();
client.Close();
Main(args);
}
Stream stream = client.GetStream();
Console.Write("Please enter a username: ");
string usrn = Console.ReadLine();
Console.Write("\n");
byte[] data = new byte[3 + usrn.Length*2];
data[0] = (byte)2;
data[1] = (byte)29;
gb(usrn).CopyTo(data, 2);
stream.Write(data, 0, data.Length);
Console.ReadKey();
}
public static byte[] gb(String str)
{
return System.Text.ASCIIEncoding.ASCII.GetBytes(str);
}
Here is how the packet should look like:
http://www.wiki.vg/Protocol#Handshake_.280x02.29
I'm ignoring server host and server port since the other bots didnt use it. (although they didnt work to :/
Here's what the original client packet holds:
'shows weird goto: https://dl.dropbox.com/u/32828727/packetsocketsminecraft.txt '
timboiscool9 (my username)
192.168.178.1 (server ip)
There's more after that but this is what i need.
I am fairly new to sockets and tcpclients
I cleaned up your code a bit:
static void Main(string[] args)
{
bool keepTrying = true;
while (keepTrying)
{
Console.Write("Enter server IP Address: ");
IPAddress ip;
if(!IPAddress.TryParse(Console.ReadLine(), out ip))
{
Console.WriteLine("Invalid ip entered, defaulting to 192.168.178.11");
ip = IPAddress.Parse("192.168.178.11");
}
Console.Write("Enter server port: ");
Int16 port;
if(!Int16.TryParse(Console.ReadLine(), out port))
{
Console.WriteLine("Invalid port entered, defaulting to 1234");
port = 1234;
}
Console.WriteLine("Connecting.....");
try
{
TcpClient client = new TcpClient();
client.Connect(new IPEndPoint(ip, port));
client.NoDelay = false;
Console.WriteLine("Connection succesfull!");
List<byte> data = new List<byte>() { 2, 29 };
Console.Write("Please enter a username: ");
byte[] userName = ASCIIEncoding.ASCII.GetBytes(Console.ReadLine());
data.AddRange(userName);
using (var stream = client.GetStream())
{
stream.Write(data.ToArray(), 0, data.Count);
Console.Write("Data sent!");
}
keepTrying = false;
}
catch
{
Console.WriteLine("--== ERROR CONNECTING ==--");
Console.WriteLine();
}
}
}
As for your original question, we need more information. You say that the packet sniffer shows no data but then you say the data has a size. So are you seeing data or not? Are you sure the server is up? The code I posted works for me, meaning it connects to a server on my local system and sends the bytes.
This is a bit old, but I'll still see if I can help you out.
The Minecraft protocol is quite complicated, and you will not be able to connect to Minecraft servers without implementing the vast majority of it. The protocol details can be found here.
I suggest you consider going a different route. Because of how complex Minecraft is, I'd avoid implementing it yourself. Luckily, I'm a Minecraft enthusiast, and I've done most of the work for you. I suggest you take a look at the Craft.Net library. It contains a full protocol implementation and making a chat bot from it would be trivial. In fact, here's an example chat program using Craft.Net for you to peruse.

Categories

Resources