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);
}
Related
I create a TCP connection between a server and a client, but after few requests I have this error message :
System.Net.Sockets.SocketException: 'An existing connection was forcibly closed by the remote host'
On this line :
_clientSocket.Send(buffer,0,buffer.Length,SocketFlags.None);
How can I resolve this error ?
Server code
private static Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private static List<Socket> _clientSockets = new List<Socket>();
private static byte[] _buffer = new byte[1024];
protected override void OnStart(string[] args)
{
SetupServer();
}
private static void SetupServer()
{
Log.writeEventLog("Setting up server...");
_serverSocket.Bind(new IPEndPoint(IPAddress.Any, 100));
_serverSocket.Listen(1);// max listen client
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
private static void AcceptCallback(IAsyncResult AR)
{
Socket socket = _serverSocket.EndAccept(AR);
_clientSockets.Add(socket);
Log.writeEventLog("Client connected");
socket.BeginReceive(_buffer,0,_buffer.Length,SocketFlags.None,new AsyncCallback(ReceiveCallback),socket);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
private static void ReceiveCallback(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
int received = socket.EndReceive(AR);
byte[] dataBuf = new byte[received];
Array.Copy(_buffer,dataBuf,received);
string text = Encoding.ASCII.GetString(dataBuf);
Log.writeEventLog("TEXT RECEIVED: " + text);
string response = string.Empty;
if(text.ToLower() != "get authentication key")
{
response = "Invalid Request";
}
else
{
response = "TEST";
}
byte[] data = Encoding.ASCII.GetBytes(response);
socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallBack), null);
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
}
private static void SendCallBack(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
socket.EndSend(AR);
}
Client code
private static Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
static void Main(string[] args)
{
LoopConnect();
SendLoop();
Console.ReadLine();
Console.ReadKey();
}
private static void SendLoop()
{
while (true)
{
Console.WriteLine("Enter a request: ");
string req = Console.ReadLine();
byte[] buffer = Encoding.ASCII.GetBytes(req);
_clientSocket.Send(buffer,0,buffer.Length,SocketFlags.None);
var receivedBuffer = new byte[2048];
int rec = _clientSocket.Receive(receivedBuffer,SocketFlags.None);
byte[] data = new byte[rec];
Array.Copy(receivedBuffer, data, rec);
Console.WriteLine("Received : " + Encoding.ASCII.GetString(data));
}
}
private static void LoopConnect()
{
int attempts = 0;
while (!_clientSocket.Connected)
{
try
{
attempts++;
_clientSocket.Connect(IPAddress.Loopback, 100);
}
catch (SocketException) {
Console.Clear();
Console.WriteLine("Connection attenpts: "+ attempts.ToString());
}
}
Console.Clear();
Console.WriteLine("Connected");
}
Update:
socket.BeginSend(data, 0, data.Length, SocketFlags.None,
new AsyncCallback(SendCallBack), socket);
I have a simple server-client socket apps which are used for send/receive files. I need to cover situation when connection is lost (I am using TCPView to crash it) using treads. So, using threads is a MUST situation and I am not sure how to do that. Here is my code for client and server side. Thanks.
Client:
public static void StartClient()
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
byte[] msg;
try
{
IPAddress ipAd = IPAddress.Parse("127.0.0.1");
IPEndPoint remoteEP = new IPEndPoint(ipAd, 1234);
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
sender.Connect(remoteEP);
Console.WriteLine("Client connected to {0}", sender.RemoteEndPoint.ToString());
Console.WriteLine("Sending file...");
msg = File.ReadAllBytes(#"C:\TCPIP\test_big.txt");
byte[] msgLengthBytes = BitConverter.GetBytes(msg.Length-3);
int msgLength = BitConverter.ToInt32(msgLengthBytes, 0);
Console.WriteLine("int: {0}", msgLength);
Console.WriteLine("msgL size: {0}", msgLengthBytes.Length);
//join arrays
byte[] result = new byte[msgLengthBytes.Length + msgLength];
Buffer.BlockCopy(msgLengthBytes, 0, result, 0, msgLengthBytes.Length);
Buffer.BlockCopy(msg, 3, result, msgLengthBytes.Length, msgLength);
int bytesSent = sender.Send(result);
Console.WriteLine("result size: {0}", result.Length);
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static void Main(String[] args)
{
StartClient();
}
Server:
public static void Main(String[] args)
{
StartListening();
}
public static void StartListening()
{
byte[] bytes = new Byte[1024];
while (true)
{
Console.WriteLine("Waiting for a connection...");
Socket handler = SocketInstance().Accept();
data = null;
//for the TCP header, get file information
bytes = new byte[4];
int bytesReceived = handler.Receive(bytes);
int Lenght = BitConverter.ToInt32(bytes, 0);
Console.WriteLine("msg length: " + Lenght);
int TotalReceivedBytes = 0;
while (TotalReceivedBytes < Lenght)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
TotalReceivedBytes = TotalReceivedBytes + bytesRec;
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
}
Console.WriteLine("Bytes received total: " + TotalReceivedBytes);
File.WriteAllText(outputPath, data);
Console.WriteLine(File.Exists(outputPath) ? "File received." : "File not received.");
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
private static Socket SocketInstance()
{
IPAddress ipAd = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndPoint = new IPEndPoint(ipAd, 1234);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(10);
return listener;
}
I am trying to create asynchronous socket client in multithreaded environment but it is not working correctly.
As below sample code,
If i create new AsyncSocketClient and call StartClent from multi-threaded environment it will process only one or two for rest, it is not processing.(I am creating new AsyncSocketClient with every new request)
Is it because of static variables,
class AsyncSocketClient
{
private static AutoResetEvent sendDone =
new AutoResetEvent(false);
private static AutoResetEvent receiveDone =
new AutoResetEvent(false);
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
static private String response = "";
public void StartClent()
{
Socket workSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// clientSock.ReceiveTimeout = 1;
try
{
workSocket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 8080), new AsyncCallback(ConnectCallBack), workSocket);
connectDone.WaitOne();
Send(s.workSocket, "<EOF>");
sendDone.WaitOne();
Receive(workSocket);
receiveDone.WaitOne();
}
catch(Exception ex)
{
}
}
private void ConnectCallBack(IAsyncResult ar)
{
Socket workSocket = (Socket)ar.AsyncState;
workSocket.EndConnect(ar);
connectDone.Set();
}
private void Receive(Socket client)
{
StateObject state = new StateObject();
state.workSocket = client;
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallBack), state);
}
private void ReceiveCallBack(IAsyncResult ar)
{
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
int byteReceived= client.EndReceive(ar);
if (byteReceived > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, state.buffer.Length));
Array.Clear(state.buffer, 0, state.buffer.Length);
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallBack), state);
}
else
{
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
receiveDone.Set();
}
}
private void Send(Socket client,string data)
{
byte[] sendBufer = Encoding.ASCII.GetBytes(data);
client.BeginSend(sendBufer, 0, sendBufer.Length, 0, new AsyncCallback(BeginSendCallBack), client);
}
private void BeginSendCallBack(IAsyncResult ar)
{
Socket client = (Socket)ar.AsyncState;
int byteSent= client.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", byteSent);
sendDone.Set();
}
}
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 30;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
Here is an example of a non blocking client and server with a simple echo implemented. There is no error checking and nothing is closed correctly which should be done. The server has some synchronous code just to make it easier to follow.
Client
public class AsyncClient
{
private const int Port = 9999;
private readonly string _clientId;
private readonly Random _random;
public AsyncClient(int clientId)
{
_clientId = string.Format("Client Id: {0}", clientId);
_random = new Random(clientId);
}
public void StartClient()
{
try
{
var workSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var state = new ClientState { WorkSocket = workSocket };
workSocket.BeginConnect(new IPEndPoint(IPAddress.Loopback, Port), ConnectCallBack, state);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void ConnectCallBack(IAsyncResult ar)
{
var state = (ClientState) ar.AsyncState;
state.WorkSocket.EndConnect(ar);
Send(state);
}
private void Receive(ClientState clientState)
{
clientState.WorkSocket.BeginReceive(clientState.Buffer, 0, ClientState.BufferSize, 0, ReceiveCallBack, clientState);
}
private void ReceiveCallBack(IAsyncResult ar)
{
var state = (ClientState) ar.AsyncState;
Socket client = state.WorkSocket;
int byteReceived= client.EndReceive(ar);
if (byteReceived > 0)
{
var receivedString = Encoding.UTF8.GetString(state.Buffer, 0, byteReceived);
Console.WriteLine("From Server: " + receivedString);
Array.Clear(state.Buffer, 0, state.Buffer.Length);
state.Count++;
Thread.Sleep(1000 + _random.Next(2000));
Send(state);
}
}
private void Send(ClientState clientState)
{
Console.WriteLine("Sending " + _clientId);
byte[] buffer = Encoding.UTF8.GetBytes(string.Format("Send from Thread {0} Client id {1} Count {2}", Thread.CurrentThread.ManagedThreadId, _clientId,clientState.Count));
clientState.WorkSocket.BeginSend(buffer, 0, buffer.Length, 0, BeginSendCallBack, clientState);
}
private void BeginSendCallBack(IAsyncResult ar)
{
var state = (ClientState) ar.AsyncState;
int byteSent= state.WorkSocket.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", byteSent);
Receive(state);
}
}
public class ClientState
{
// Client socket.
public Socket WorkSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] Buffer = new byte[BufferSize];
public int Count = 0;
}
Server
public class AsyncServer
{
private const int Port = 9999;
public void StartServer()
{
var thread = new Thread(Run) {IsBackground = true};
thread.Start();
}
private void Run()
{
Console.WriteLine("Running");
var tcpListener = new TcpListener(IPAddress.Loopback, Port);
tcpListener.Start();
while (true)
{
Console.WriteLine("Before Accept");
var state = new ServerState {WorkSocket = tcpListener.AcceptSocket()};
Console.WriteLine("Before Recieve");
Receive(state);
}
}
private void Receive(ServerState state)
{
state.WorkSocket.BeginReceive(state.Buffer, 0, ServerState.BufferSize, 0, ReceiveCallBack, state);
}
private void ReceiveCallBack(IAsyncResult ar)
{
Console.WriteLine("ReceiveCallBack");
var state = (ServerState) ar.AsyncState;
try
{
int byteReceived= state.WorkSocket.EndReceive(ar);
if (byteReceived > 0)
{
var receivedString = Encoding.UTF8.GetString(state.Buffer, 0, byteReceived);
Console.WriteLine("Received: " + receivedString);
var bytesToSend = Encoding.UTF8.GetBytes("Server Got --> " + receivedString);
Array.Copy(bytesToSend, state.Buffer, bytesToSend.Length);
state.WorkSocket.Send(state.Buffer, 0, bytesToSend.Length, SocketFlags.None);
Array.Clear(state.Buffer, 0, state.Buffer.Length);
Receive(state);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
private class ServerState
{
public const int BufferSize = 1024;
public readonly byte[] Buffer = new byte[1024];
public Socket WorkSocket;
}
I have run this using a console you can either have two applications or just launch the client and server separately.
static void Main(string[] args)
{
if (args.Length != 0)
{
var server = new AsyncServer();
server.StartServer();
}
else
{
for(int i = 0; i < 10; i++)
{
var client = new AsyncClient(i);
client.StartClient();
}
}
Console.WriteLine("Press a key to exit");
Console.ReadKey();
}
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);
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.