I created a .NET class socket using a websocket server. When my browser tries to connect to socket on my program, I see that the method 'accept socket' is called very slow or seconds after my browser connects. I tried creating many connections but the socket accepts a websocket every second. I tried alchemy websocket too, results like my code.
After I used Miscrosoft websocket on IIS8, I noticed that the speed is pretty good.
I am not experimental.
My code (express)
class Connection
{
byte[] buffer = new byte[1024];
Socket socket;
bool IsAuthencation;
public Connection(Socket socket)
{
this.socket = socket;
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
}
void OnReceive(IAsyncResult result)
{
try
{
int count = socket.EndReceive(result);
if (count != 0)
{
if (!IsAuthencation)
{
byte[] tmp = new byte[count];
Array.Copy(buffer, 0, tmp, 0, count);
string Request = Encoding.UTF8.GetString(tmp);
if (Request.Contains("GET"))
{
if (!IsAuthencation)
{
int indexStart = Request.IndexOf("Sec-WebSocket-Key: ");
int indexEnd = Request.IndexOf("Sec-WebSocket-Version:");
string key = Request.Substring(indexStart + 19, indexEnd - indexStart - 21);
string magic = string.Concat(key, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
string base64 = "";
using (SHA1 sha1 = SHA1.Create())
{
byte[] bufferMagic = sha1.ComputeHash(Encoding.UTF8.GetBytes(magic));
base64 = Convert.ToBase64String(bufferMagic);
}
Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine
+ "Connection: Upgrade" + Environment.NewLine
+ "Upgrade: websocket" + Environment.NewLine
+ "Sec-WebSocket-Accept: " + base64
+ Environment.NewLine
+ Environment.NewLine);
socket.BeginSend(response, 0, response.Length, SocketFlags.None, new AsyncCallback(OnSend), null);
IsAuthencation = true;
}
}
}
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnReceive), null);
}
else
{
// disconnect
}
}
catch (Exception)
{
}
}
void OnSend(IAsyncResult result)
{
try
{
socket.EndSend(result);
}
catch (Exception)
{
}
}
}
class Program
{
static List<Connection> clients;
static Socket socket;
static void Main(string[] args)
{
clients = new List<Connection>();
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 30000);
socket.Bind(endPoint);
socket.Listen(0);
socket.BeginAccept(new AsyncCallback(AcceptAsync), null);
Console.ReadLine();
}
static void AcceptAsync(IAsyncResult result)
{
Console.WriteLine("a new connection");
Socket s = socket.EndAccept(result);
clients.Add(new Connection(s));
socket.BeginAccept(new AsyncCallback(AcceptAsync), null);
}
}
you can try command javascript var socket= new WebSocket("ws://localhost:30000"), i not see a problem in my code.
Thanks
You have to accept the socket, and handle it asynchronously, and then back to accepting more sockets straightaway.
UPDATE
After seeing your code, it seems you are accepting connections asynchronously. How are you creating those test connections? If you are creating too many you are maybe saturating the app.
I think I see the problem, why are you setting the socket backlog to 0? Read this answer from SO.
Try to put a bigger value: socket.Listen(100);
Related
I am working on a Master - Slave kind of network relationship between a server and multiple clients.
The server is fine, the problem is that i am new to TCP and do not know how to connect to the server without the client knowing the ip form the start.
If someone could rewrite some of my code so it works, I would be thankful.
The server
namespace Server
{
class Program
{
static void Main(string[] args)
{
TcpListener listen = new TcpListener(IPAddress.Any, 8001);
TcpClient clientSocket = default(TcpClient);
int counter = 0;
listen.Start();
Console.WriteLine(" >> " + "Server Started");
while (true)
{
counter += 1;
clientSocket = listen.AcceptTcpClient();
HandleClinet client = new HandleClinet();
client.startClient(clientSocket, Convert.ToString(counter));
}
}
}
public class HandleClinet
{
TcpClient clientSocket;
string clNo;
public void startClient(TcpClient inClientSocket, string clineNo)
{
clientSocket = inClientSocket;
clNo = clineNo;
Thread ClientThread = new Thread(DoChat);
ClientThread.Start();
}
private void DoChat()
{
byte[] bytesFrom = new byte[1024];
string dataFromClient = null;
byte[] sendBytes = null;
string serverResponse = null;
while ((true))
{
try
{
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Read(bytesFrom, 0, 1024);
dataFromClient = Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("\0"));
Console.WriteLine(" >> " + "From client-" + clNo + " " + dataFromClient);
serverResponse = Console.ReadLine();
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
}
catch (Exception ex)
{
throw;
}
}
}
}
}
The client
namespace Client
{
class Program
{
public static TcpClient tcpclnt = new TcpClient();
static void Main(string[] args)
{
while(true)
{
LoopConnect();
LoopPacket();
tcpclnt.Close();
}
}
private static void LoopPacket()
{
byte[] bytesFrom = new byte[1024];
string dataFromClient = null;
byte[] sendBytes = null;
string serverResponse = null;
while ((true))
{
try
{
NetworkStream networkStream = tcpclnt.GetStream();
serverResponse = "Give me a command!";
sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Read(bytesFrom, 0, 1024);
dataFromClient = Encoding.ASCII.GetString(bytesFrom);
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("\0"));
Console.WriteLine(" >> " + "From server -" + dataFromClient);
networkStream.Flush();
}
catch (Exception ex)
{
throw;
}
}
}
private static void LoopConnect()
{
Console.WriteLine("Connecting.....");
while(true)
{
try
{
tcpclnt.Connect(IPAddress.Any, 8001); // The problem area
break;
}
catch (Exception)
{
Console.Write(".");
}
}
Console.WriteLine("Connected.");
}
}
}
The client should somehow get address of the server. The method is depending on the network type (local or Internet). In case of Internet it's virtually impossible without some known peer. In case of a local network you could use a broadcast UDP request (this method is depending on the local network routing rules).
I am setting up a server to read some network clients using TcpListener. The Client sends some data I verify that data and send a response to that data, the client stays connected and sends a second response and I verify that data and send a response back, its like logging in to the server twice. The first login get sent back to the client just fine but the second time the client responds the server does not show that it received anymore data from the client.
I have tested it by setting up a dummy client (the real client is Cell phone based ODB2). With the dummy client set up I did verify that the first handshake happens but the when the client sends the second set of text it does not show up on the server.
class Program
{
static private TcpListener listener = null;
static private TcpClient client = null;
static private NetworkStream stream = null;
static private int iCount = 0;
static Int32 port = 8090;
static IPAddress localAddr = IPAddress.Parse("192.168.1.17");
static void Main(string[] args)
{
listener = new TcpListener(localAddr, port);
listener.Start();
while (true)
{
try
{
client = listener.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(ThreadProc, client);
}
catch (IOException ioex)
{
RestartStream();
}
}
}
private static void ThreadProc(object obj)
{
var client = (TcpClient)obj;
Byte[] bytes = new Byte[client.ReceiveBufferSize];
stream = client.GetStream();
try
{
int bytesRead = stream.Read(bytes, 0, (int)client.ReceiveBufferSize);
string returndata = Encoding.ASCII.GetString(bytes, 0, bytesRead).Replace("-", "");
byte[] sendBytes;
if (returndata.ToLower().StartsWith("7e") && returndata.ToLower().EndsWith("7e"))
{
//… do stuff with the data and send it back to the client
sendBytes = Encoding.Default.GetBytes(login1);
stream.Write(sendBytes, 0, sendBytes.Length);
stream.Flush();
}
else
{
SaveStream(returndata);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Test Client Code:
//---data to send to the server---
string textToSend = "7E010000360141850000080000000000000000000000000000000000000000000000000000000000000035303030303038003131313131313131313131313131313131F67E";
//---create a TCPClient object at the IP and port no.---
TcpClient client = new TcpClient(SERVER_IP, PORT_NO);
NetworkStream nwStream = client.GetStream();
byte[] bytesToSend = ASCIIEncoding.ASCII.GetBytes(textToSend);
//---send the text---
Console.WriteLine("Sending : " + textToSend);
nwStream.Write(bytesToSend, 0, bytesToSend.Length);
//---read back the text---
byte[] bytesToRead = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(bytesToRead, 0, client.ReceiveBufferSize);
Console.WriteLine("Received : " + Encoding.ASCII.GetString(bytesToRead, 0, bytesRead));
string Text2 = "7E0100003601418535303030303038003131313131313131313131313131313131F67E";
Console.WriteLine("Sending : " + Text2);
byte[] bytesToSend2 = ASCIIEncoding.ASCII.GetBytes(Text2);
nwStream.Write(bytesToSend2, 0, bytesToSend2.Length);
client.Close();
Console.ReadLine();
What I need to happen is my understanding is the client stays connected the whole time and send data over and over, my system seems to accept it once and then stops receiving it, I need it to continue to receive the client data and process it.
Ok so I figured it out, there should be a second while loop in side the thread.
static void Main(string[] args)
{
listener = new TcpListener(localAddr, port);
var clientSocket = default(TcpClient);
listener.Start();
var counter = 0;
while (true)
{
clientSocket = listener.AcceptTcpClient();
var client = new ConnectedDevice();
client.startClient(clientSocket, counter.ToString(), sqlConnString);
}
}
ConnectedDevice class:
class ConnectedDevice
{
private TcpClient _clientSocket;
private string _clientNumber;
private string _sqlConnString;
public void startClient(TcpClient clientSocket, string clientNumber, string sqlConnString)
{
_clientSocket = clientSocket;
_clientNumber = clientNumber;
_sqlConnString = sqlConnString;
var ctThread = new Thread(ProcessClient);
ctThread.Start();
}
private void ProcessClient()
{
while (_clientSocket.Connected)
{
try
{
Byte[] bytes = new Byte[_clientSocket.ReceiveBufferSize];
var networkStream = _clientSocket.GetStream();
networkStream.ReadTimeout = 10000;
int i;
while ((i = networkStream.Read(bytes, 0, bytes.Length)) != 0)
{
var data = System.Text.Encoding.ASCII.GetString(bytes, 0, i).Replace("-", "");
byte[] sendBytes;
Console.WriteLine(data);
string sLogin1 = "7E81000013014185000008000000000054523230313731303138303930303137497E";
sendBytes = Encoding.ASCII.GetBytes(sLogin1);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
}
}
catch (Exception ex)
{
}
}
}
}
I have two basic console apps that communicate "over the network" even though all of the communication takes place on my local machine.
Client code:
public static void Main()
{
while (true)
{
try
{
TcpClient client = new TcpClient();
client.Connect("127.0.0.1", 500);
Console.WriteLine("Connected.");
byte[] data = ASCIIEncoding.ASCII.GetBytes(new FeederRequest("test", TableType.Event).GetXmlRequest().ToString());
Console.WriteLine("Sending data.....");
using (var stream = client.GetStream())
{
stream.Write(data, 0, data.Length);
stream.Flush();
Console.WriteLine("Data sent.");
}
client.Close();
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.StackTrace);
Console.ReadLine();
}
}
}
Server code:
public static void Main()
{
try
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
Console.WriteLine("Starting TCP listener...");
TcpListener listener = new TcpListener(ipAddress, 500);
listener.Start();
Console.WriteLine("Server is listening on " + listener.LocalEndpoint);
while (true)
{
Socket client = listener.AcceptSocket();
Console.WriteLine("\nConnection accepted.");
var childSocketThread = new Thread(() =>
{
Console.WriteLine("Reading data...\n");
byte[] data = new byte[100];
int size = client.Receive(data);
Console.WriteLine("Recieved data: ");
for (int i = 0; i < size; i++)
Console.Write(Convert.ToChar(data[i]));
//respond to client
Console.WriteLine("\n");
client.Close();
Console.WriteLine("Waiting for a connection...");
});
childSocketThread.Start();
}
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.StackTrace);
Console.ReadLine();
}
}
How can I alter both of these applications so that when the Server has received the data, it responds to the Client with some kind of confirmation?
Thanks in advance!
Here a short example how I would do it:
Server:
class Server
{
static void Main(string[] args)
{
TcpListener listener = new TcpListener(IPAddress.Any, 1500);
listener.Start();
TcpClient client = listener.AcceptTcpClient();
NetworkStream stream = client.GetStream();
// Create BinaryWriter for writing to stream
BinaryWriter binaryWriter = new BinaryWriter(stream);
// Creating BinaryReader for reading the stream
BinaryReader binaryReader = new BinaryReader(stream);
while (true)
{
// Read incoming information
byte[] data = new byte[16];
int receivedDataLength = binaryReader.Read(data, 0, data.Length);
string stringData = Encoding.ASCII.GetString(data, 0, receivedDataLength);
// Write incoming information to console
Console.WriteLine("Client: " + stringData);
// Respond to client
byte[] respondData = Encoding.ASCII.GetBytes("respond");
Array.Resize(ref respondData, 16); // Resizing to 16 byte, because in this example all messages have 16 byte to make it easier to understand.
binaryWriter.Write(respondData, 0, 16);
}
}
}
Client:
class Client
{
private static void Main(string[] args)
{
Console.WriteLine("Press any key to start Client");
while (! Console.KeyAvailable)
{
}
TcpClient client = new TcpClient();
client.Connect("127.0.0.1", 1500);
NetworkStream networkStream = client.GetStream();
// Create BinaryWriter for writing to stream
BinaryWriter binaryWriter = new BinaryWriter(networkStream);
// Creating BinaryReader for reading the stream
BinaryReader binaryReader = new BinaryReader(networkStream);
// Writing "test" to stream
byte[] writeData = Encoding.ASCII.GetBytes("test");
Array.Resize(ref writeData, 16); // Resizing to 16 byte, because in this example all messages have 16 byte to make it easier to understand.
binaryWriter.Write(writeData, 0, 16);
// Reading response and writing it to console
byte[] responeBytes = new byte[16];
binaryReader.Read(responeBytes, 0, 16);
string response = Encoding.ASCII.GetString(responeBytes);
Console.WriteLine("Server: " + response);
while (true)
{
}
}
}
I hope this helps! ;)
You can perform both Read and Write on the same stream.
After you send all the data over, just call stream.Read as in
using (var stream = client.GetStream())
{
stream.Write(data, 0, data.Length);
stream.Flush();
Console.WriteLine("Data sent.");
stream.Read(....); //added sync read here
}
MSDN documentation on TcpClient has an example as well http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx
If you want feed back such as reporting # of bytes received so far, you'll have to use async methods.
Here's an example of what (I think) you want to do:
static void Main(string[] args) {
var server = new Task(Server);
server.Start();
System.Threading.Thread.Sleep(10); // give server thread a chance to setup
try {
TcpClient client = new TcpClient();
client.Connect("127.0.0.1", 1500);
Console.WriteLine("Connected.");
var data = new byte[100];
var hello = ASCIIEncoding.ASCII.GetBytes("Hello");
Console.WriteLine("Sending data.....");
using (var stream = client.GetStream()) {
stream.Write(hello, 0, hello.Length);
stream.Flush();
Console.WriteLine("Data sent.");
// You could then read data from server here:
var returned = stream.Read(data, 0, data.Length);
var rec = new String(ASCIIEncoding.ASCII.GetChars(data, 0, data.Length));
rec = rec.TrimEnd('\0');
if (rec == "How are you?") {
var fine = ASCIIEncoding.ASCII.GetBytes("fine and you?");
stream.Write(fine, 0, fine.Length);
}
}
client.Close();
Console.ReadLine();
}
catch (Exception e) {
Console.WriteLine("Error: " + e.StackTrace);
Console.ReadLine();
}
}
public static void Server() {
try {
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
Console.WriteLine("*Starting TCP listener...");
TcpListener listener = new TcpListener(ipAddress, 1500); // generally use ports > 1024
listener.Start();
Console.WriteLine("*Server is listening on " + listener.LocalEndpoint);
Console.WriteLine("*Waiting for a connection...");
while (true) {
Socket client = listener.AcceptSocket();
while (client.Connected) {
Console.WriteLine("*Connection accepted.");
Console.WriteLine("*Reading data...");
byte[] data = new byte[100];
int size = client.Receive(data);
Console.WriteLine("*Recieved data: ");
var rec = new String(ASCIIEncoding.ASCII.GetChars(data, 0, size));
rec = rec.TrimEnd('\0');
Console.WriteLine(rec);
if (client.Connected == false) {
client.Close();
break;
}
// you would write something back to the client here
if (rec == "Hello") {
client.Send(ASCIIEncoding.ASCII.GetBytes("How are you?"));
}
if (rec == "fine and you?") {
client.Disconnect(false);
}
}
}
listener.Stop();
}
catch (Exception e) {
Console.WriteLine("Error: " + e.StackTrace);
Console.ReadLine();
}
}
}
Keep in mind that data sent via sockets can arrive fragmented (in different packets). This doesn't usually happen with the packets are small.
static void Main(string[] args)
{
Console.Title = "Socket Server";
Console.WriteLine("Listening for client messages");
Socket serverSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
IPAddress serverIp = IPAddress.Any;
IPEndPoint serverEP = new IPEndPoint(serverIp, 8000);
SocketPermission socketPermission = new SocketPermission(NetworkAccess.Accept,
TransportType.Tcp,
"127.0.0.1", 8000);
serverSocket.Bind(serverEP);
serverSocket.Listen(2);
while(true)
{
//Socket connection = serverSocket.Accept();
connection = serverSocket.Accept();
Thread clientThread = new Thread(new ParameterizedThreadStart(MultiUser));
clientThread.Start(connection);
}
}
public static void MultiUser(object connection)
{
byte[] serverBuffer = new byte[10025];
string message = string.Empty;
int bytes = ((Socket)connection).Receive(serverBuffer, serverBuffer.Length, 0);
message += Encoding.ASCII.GetString(serverBuffer, 0, bytes);
Console.WriteLine(message);
TcpClient client = new TcpClient();
client.Client = ((Socket)connection);
IntPtr handle = client.Client.Handle;
}
I want to write a chat program which has one server and 2 clients. The problem is that, I can not direct the message sent from the client1 to client2 via the server. How can the server distinguish threads so that it can send the received message from client1 to client2?
Each client has their own handle. You can access this via the Handle property. For example:
TcpClient client = tcpListener.AcceptTcpClient();
IntPtr handle = client.Client.Handle; //returns a handle to the connection
Then all you need to do is store this in a hashtable, and iterate through it, looking for available data. When you detect data on the wire for one of the connections, then save it and retransmit it to the other clients in the table.
Remember to make sure that you make this multithreaded so a listen request on one client does not block any send or receive functions on other clients!
I've added some code here you should be able to work with (tested it out on my system)
private void HandleClients(object newClient)
{
//check to see if we are adding a new client, or just iterating through existing clients
if (newClient != null)
{
TcpClient newTcpClient = (TcpClient)newClient;
//add this client to our list
clientList.Add(newTcpClient.Client.Handle, newTcpClient);
Console.WriteLine("Adding handle: " + newTcpClient.Client.Handle); //for debugging
}
//iterate through existing clients to see if there is any data on the wire
foreach (TcpClient tc in clientList.Values)
{
if (tc.Available > 0)
{
int dataSize = tc.Available;
Console.WriteLine("Received data from: " + tc.Client.Handle); //for debugging
string text = GetNetworkString(tc.GetStream());
//and transmit it to everyone else
foreach (TcpClient otherClient in clientList.Values)
{
if (tc.Client.Handle != otherClient.Client.Handle)
{
Send(otherClient.GetStream(), text);
}
}
}
}
}
public void Send(NetworkStream ns, string data)
{
try
{
byte[] bdata = GetBytes(data, Encoding.ASCII);
ns.Write(bdata, 0, bdata.Length);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
protected string GetNetworkString(NetworkStream ns)
{
if (ns.CanRead)
{
string receivedString;
byte[] b = GetNetworkData(ns);
receivedString = System.Text.Encoding.UTF8.GetString(b);
log.Info("Received string: " + receivedString);
return receivedString;
}
else
return null;
}
protected byte[] GetNetworkData(NetworkStream ns)
{
if (ns.CanRead)
{
log.Debug("Data detected on wire...");
byte[] b;
byte[] myReadBuffer = new byte[1024];
MemoryStream ms = new MemoryStream();
int numberOfBytesRead = 0;
// Incoming message may be larger than the buffer size.
do
{
numberOfBytesRead = ns.Read(myReadBuffer, 0, myReadBuffer.Length);
ms.Write(myReadBuffer, 0, numberOfBytesRead);
}
while (ns.DataAvailable);
//and get the full message
b = new byte[(int)ms.Length];
ms.Seek(0, SeekOrigin.Begin);
ms.Read(b, 0, (int)ms.Length);
ms.Close();
return b;
}
else
return null;
}
You will want to call HandleClients from a main thread that checks to see if there are any pending requests or not, and runs on a loop.
this is my code for Monitoring Http:
static void Main(string[] args)
{
try
{
byte[] input = BitConverter.GetBytes(1);
byte[] buffer = new byte[4096];
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
s.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 80));
s.IOControl(IOControlCode.ReceiveAll, input, null);
s.BeginReceive(arrResponseBytes, 0, arrResponseBytes.Length, SocketFlags.None, new AsyncCallback(OnClientReceive), s);
System.Threading.ManualResetEvent reset = new System.Threading.ManualResetEvent(false);
reset.WaitOne();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadKey();
}
static byte[] arrResponseBytes = new byte[1024 * 5];
protected static void OnClientReceive(IAsyncResult ar)
{
Socket socket = (Socket)ar.AsyncState;
int count = socket.EndReceive(ar);
if (count > 0)
{
Console.WriteLine(Encoding.ASCII.GetString(arrResponseBytes, 0, count));
socket.BeginReceive(arrResponseBytes, 0, arrResponseBytes.Length, SocketFlags.None, new AsyncCallback(OnClientReceive), socket);
}
}
but i cannot get http hosts.
I do not know what data.
i want to get http host for example:
http://google.com
how can i monitor system http?
thanks.
What you see in your link is the IP + TCP headers. You should parse the IP&TCP headers to extract the content. TCP content starts approximately at offset 40. So you can try your program's modified version as below to see the content of each HTTP request. (Working but not complete program just to give you an idea)
PS: See the s.Bind(new IPEndPoint(IPAddress.Broadcast, 80));
static void Main(string[] args)
{
try
{
byte[] input = new byte[]{1};
byte[] buffer = new byte[4096];
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
s.Bind(new IPEndPoint(IPAddress.Broadcast, 80));
s.IOControl(IOControlCode.ReceiveAll , input, null);
s.BeginReceive(arrResponseBytes, 0, arrResponseBytes.Length, SocketFlags.None, new AsyncCallback(OnClientReceive), s);
System.Threading.ManualResetEvent reset = new System.Threading.ManualResetEvent(false);
reset.WaitOne();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
Console.ReadKey();
}
static byte[] arrResponseBytes = new byte[1024 * 64];
static void OnClientReceive(IAsyncResult ar)
{
Socket socket = (Socket)ar.AsyncState;
int count = socket.EndReceive(ar);
if (count >= 40)
{
try
{
string s = Encoding.UTF8.GetString(arrResponseBytes, 40, count - 40);
string bin = BitConverter.ToString(arrResponseBytes, 40, count - 40).Replace("-", " ");
if(s.StartsWith("GET"))
Console.WriteLine(s + " - " + bin);
//Thread.Sleep(1000);
}
catch { }
}
socket.BeginReceive(arrResponseBytes, 0, arrResponseBytes.Length, SocketFlags.None, new AsyncCallback(OnClientReceive), socket);
}