C# client can not write message to server, I think the parsing byte to string is bad. I connect in client class with the connect method via ipaddress and port. However I start the compile the server don't change, but client will turn off.
Here is my Server:
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
this.tcpListener = new TcpListener(IPAddress.Parse("10.0.0.44"), 3000);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
Thread clientThreadSend = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
clientThreadSend.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
TcpClient sendClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
Console.WriteLine("To: " + tcpClient.Client.LocalEndPoint);
Console.WriteLine("From: " + tcpClient.Client.RemoteEndPoint);
Console.WriteLine(encoder.GetString(message, 0, bytesRead));
clientStream.Flush();
sendToClient("Test back", sendClient);
}
tcpClient.Close();
}
public void sendToClient(String line, TcpClient client)
{
try
{
NetworkStream stream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes(line + "\0");
stream.Write(buffer, 0, buffer.Length);
stream.Flush();
}
catch
{
Console.WriteLine("Client Disconnected." + Environment.NewLine);
}
}
public void broadcast(String line, TcpClient thisClient)
{
sendToClient(line, thisClient);
}
static void Main(string[] args)
{
new Server();
}
}
Here is my client:
public class Client
{
TcpClient _tcpClient;
// Connects the client to a server at the specified
// IP address and port.
public void Connect(IPAddress address, int port)
{
_tcpClient = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(address, port);
_tcpClient.Connect(serverEndPoint);
// Create a thread to read data sent from the server.
ThreadPool.QueueUserWorkItem(
delegate
{
Read();
});
}
// Sends bytes to the server.
public void Send(byte[] buffer)
{
_tcpClient.GetStream().Write(
buffer, 0, buffer.Length);
_tcpClient.GetStream().Flush();
}
public void Read()
{
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = _tcpClient.GetStream().Read(buffer, 0, 4096);
Console.WriteLine(encoder.GetString(buffer, 0, bytesRead));
}
}
public void Dispose()
{
_tcpClient.Close();
}
public static void Main(string[] args)
{
Client c = new Client();
c.Connect(IPAddress.Parse("10.0.0.44"), 3000);
}
}
Deadlock
your client is not sending the data and the server is also not able to send any data since it is getting blocked at
bytesRead = clientStream.Read(message, 0, 4096);
Related
I run client code on Unity and server code on a console application. The problem is that when the server sent a 'welcome' message to the client, the client receives an empty message. But weirdly when I run the code on Unity in debug mode it works well. Does anyone know why this happens?
Here is the client code
public class Test: MonoBehaviour
{
TcpClient client;
NetworkStream networkStream;
string stringData;
byte[] data;
private void Start()
{
StartClient();
}
private void OnApplicationQuit()
{
if (networkStream != null)
{
if (networkStream.CanRead && networkStream.CanWrite) networkStream.Close();
}
if (client.Connected) client.Close();
}
private void StartClient()
{
client = new TcpClient();
client.BeginConnect("127.0.0.1", 7777, DefaultConnectCallback, client);
}
private void DefaultConnectCallback(IAsyncResult ar)
{
TcpClient client = (TcpClient)ar.AsyncState;
networkStream = client.GetStream();
data = new byte[1024];
networkStream.BeginRead(data, 0, data.Length, DefaultReadCallback, networkStream);
stringData = System.Text.Encoding.ASCII.GetString(data).Trim('\0');
Log.LogMessage("Recieved a message");
Log.LogMessage(stringData);
Log.LogMessage($"{stringData.Length}");
}
private void DefaultReadCallback(IAsyncResult ar)
{
NetworkStream networkStream = (NetworkStream)ar.AsyncState;
networkStream.EndRead(ar);
}
}
Here is the server code
class Program
{
public static Action OnExit;
static void Main(string[] args)
{
AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);
TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 7);
listener.Start();
Log.LogMessage("Server Started");
OnExit += () =>
{
foreach(var client in clients)
{
client?.GetStream()?.Close();
}
listener.Stop();
};
listener.BeginAcceptTcpClient(DefaultAcceptCallback, listener);
Console.ReadKey();
}
static void OnProcessExit(object sender, EventArgs e)
{
if (OnExit != null) OnExit();
}
static TcpClient[] clients = new TcpClient[10];
static int connection = 0;
static void DefaultAcceptCallback(IAsyncResult ar)
{
TcpListener listener = (TcpListener)ar.AsyncState;
TcpClient newClient = listener.EndAcceptTcpClient(ar);
NetworkStream networkStream = newClient.GetStream();
byte[] welcome;
Log.LogMessage($"Connect request No.{connection} accepted");
clients[connection] = newClient;
welcome = Encoding.ASCII.GetBytes("Welcome!");
networkStream.BeginWrite(welcome, 0, welcome.Length, DefaultReadCallback, networkStream);
Log.LogMessage($"Welcome message sent");
connection++;
listener.BeginAcceptTcpClient(DefaultAcceptCallback, listener);
}
static void DefaultWriteCallback(IAsyncResult ar)
{
NetworkStream networkStream = (NetworkStream)ar.AsyncState;
networkStream.EndWrite(ar);
}
}
networkStream.BeginRead(data, 0, data.Length, DefaultReadCallback, networkStream);
is a non-blocking call and you immediately continue with your code.
You have to wait until actually something has been received!
private void DefaultConnectCallback(IAsyncResult ar)
{
TcpClient client = (TcpClient)ar.AsyncState;
networkStream = client.GetStream();
data = new byte[1024];
networkStream.BeginRead(data, 0, data.Length, DefaultReadCallback, networkStream);
}
private void DefaultReadCallback(IAsyncResult ar)
{
NetworkStream networkStream = (NetworkStream)ar.AsyncState;
networkStream.EndRead(ar);
stringData = System.Text.Encoding.ASCII.GetString(data).Trim('\0');
Log.LogMessage("Recieved a message");
Log.LogMessage(stringData);
Log.LogMessage($"{stringData.Length}");
}
See NetworkStream.BeginRead and also the example of NetworkStream.EndRead
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've got the following problem in a client socket (sync) / server socket (async) environment.
If I send multiple messages from the client to the server, the first one finishs without any problems and will be received by the client without issues. When I send the 2nd message, just a few bytes go through. It doesn't seem to be a client problem, because it looks the client sends the whole message all the time. The crazy thing is, if I completely stop the project on the client and start again the first message completes again, also if the server component runs through all the time.
What I want to do...
Basically, I want to transfer different objects, most xml structured through the network and receive it on the client. Therefore, I do the Serialization/Deserialization.
The basics of the following code are extended msdn examples.
//CLIENT:
class ProgramClient
{
static void Main(string[] args)
{
string rootNode = "config";
StreamReader configStream = new StreamReader(config);
XmlDocument xml = new XmlDocument();
xml.Load(configStream);
SynchronousSocketClient socket = new SynchronousSocketClient("192.168.0.1", 40001, "c:\\log", xml);
socket.StartClient();
socket.Dispose();
socket = new SynchronousSocketClient("192.168.0.1", 40001, "c:\\log", xml);
socket.StartClient();
socket.Dispose();
}
}
class SynchronousSocketClient : IDisposable
{
private string ip;
private int port;
private object data;
public StreamWriter log;
public event EventHandler Disposed;
public SynchronousSocketClient(string ip, int port, string logfile, object data)
{
this.ip = ip;
this.port = port;
this.data = data;
openLog(logfile);
}
public void openLog(string logfile)
{
log = new StreamWriter(logfile, true);
}
public void Dispose()
{
log.Close();
if (this.Disposed != null)
this.Disposed(this, EventArgs.Empty);
}
// Convert an object to a byte array
private byte[] Serialize(object obj)
{
Stream stream = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(stream, obj);
byte[] b = null;
b = new byte[stream.Length];
stream.Position = 0;
stream.Read(b, 0, (int)stream.Length);
stream.Close();
return b;
}
public void StartClient()
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.GetHostEntry(ip);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress,port);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
// Connect the socket to the remote endpoint. Catch any errors.
try {
sender.Connect(remoteEP);
log.WriteLine(DateTime.Now+": Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Serialize(data);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
log.WriteLine(DateTime.Now + ": {0}",
Encoding.Unicode.GetString(bytes,0,bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
} catch (ArgumentNullException ane) {
log.WriteLine(DateTime.Now + ": ArgumentNullException : {0}", ane.ToString());
} catch (SocketException se) {
log.WriteLine(DateTime.Now + ": SocketException : {0}", se.ToString());
} catch (Exception e) {
log.WriteLine(DateTime.Now + ": Unexpected exception : {0}", e.ToString());
}
} catch (Exception e) {
log.WriteLine(DateTime.Now+": "+e.ToString());
}
}
}
//SERVER:
class ProgramServer
{
static void Main(string[] args)
{
NetworkSocket socket = new NetworkSocket(nwsocketport);
socket.Start();
}
}
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of send buffer.
public const int sBufferSize = 1024;
// send buffer.
public byte[] sBuffer = new byte[sBufferSize];
// Received data object;
public object data = null;
// bytes read so far
public int bytesRead;
//receive buffer
public byte[] rBuffer;
}
public class NetworkSocket
{
private int port;
Socket listener;
IPEndPoint localEndPoint;
public NetworkSocket(int port) {
this.port = port;
}
public void Start() {
// Establish the local endpoint for the socket.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[1];
localEndPoint = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
//set socket timeouts
listener.SendTimeout = 5000;
listener.ReceiveTimeout = 5000;
// Bind the socket to the local endpoint and listen for incoming connections.
try {
listener.Bind(localEndPoint);
listener.Listen(1);
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
public void AcceptCallback(IAsyncResult ar) {
// Signal the main thread to continue.
//allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket) ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
// Data buffer for incoming data.
state.rBuffer = new Byte[listener.ReceiveBufferSize];
state.workSocket = handler;
handler.BeginReceive(state.rBuffer, 0, state.rBuffer.Length, 0,
new AsyncCallback(ReadCallback), state);
try
{
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void ReadCallback(IAsyncResult ar) {
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket handler = state.workSocket;
//handler.ReceiveTimeout = 2000;
// Read data from the client socket.
state.bytesRead = handler.EndReceive(ar);
Send(handler, "paket successfully tranferred");
state.data = Deserialize(state.rBuffer);
bool xmlDoc = true;
try
{
XDocument.Parse(state.data.ToString());
}
catch
{
xmlDoc = false;
}
if (xmlDoc)
XMLHandler.update(state.data.ToString());
}
private void Send(Socket handler, String data) {
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.Unicode.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
private void SendCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.
Socket handler = (Socket) ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
// Convert a byte array to an Object
private object Deserialize(byte[] b)
{
MemoryStream stream = new MemoryStream(b);
BinaryFormatter bf = new BinaryFormatter();
object obj = bf.Deserialize(stream);
stream.Close();
return obj;
}
// convert object to byte array
private byte[] Serialize(object obj)
{
Stream stream = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(stream, obj);
byte[] b = null;
b = new byte[stream.Length];
stream.Position = 0;
stream.Read(b, 0, (int)stream.Length);
stream.Close();
return b;
}
}
Could anybody please help me with my problem? I am not experienced in Socket Programming...
In your ReadCallback you need to start another BeginReceive, just like how you call BeginAccept in the AcceptCallback method.
A more serious issue with your code is that you expect to receive one entire message per ReadCallback. In reality, you could receive half a message, one byte, or three messages.
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.
I have an application running at remote server which writes data (string) to its local port, I want to read this systems port by another C# application running at some other system, When i connect to this port of the remote machine I get an error that the target machine actively refused the connection.
Any suggestion will be appreciated.
I have tried this code:
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var ipaddress = IPAddress.Parse("192.168.1.12");
IPAddress add = new IPAddress(ipaddress.GetAddressBytes());
EndPoint ep = new IPEndPoint(add, 7862);
sock.Connect(ep);
if (sock.Connected)
{
byte[] bytes = new byte[256];
int i = sock.Receive(bytes);
Console.WriteLine(Encoding.UTF8.GetString(bytes));
}
Here 192.168.1.12 is the IP address of the remote system, where an application is writing string continuously to port 7862. I need to read the value from that port via a C# application
I had written a program like that while ago... i copy paste it as it is, dont forget to allow "port" to the firewall and NAT so that the packet actually gets through
class Transmitter
{
public Boolean Transmit(String ip ,String port, String data){
TcpClient client = new TcpClient();
int _port = 0;
int.TryParse(port, out _port);
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(ip), _port);
client.Connect(serverEndPoint);
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes(data);
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
return true;
}
}
class Listener
{
private TcpListener tcpListener;
private Thread listenThread;
// Set the TcpListener on port 13000.
Int32 port = 8081;
IPAddress localAddr = IPAddress.Parse("192.168.1.3");
Byte[] bytes = new Byte[256];
MainWindow mainwind = null;
public void Server(MainWindow wind)
{
mainwind = wind;
this.tcpListener = new TcpListener(IPAddress.Any, port);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
// System.Windows.MessageBox.Show("socket");
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
// System.Windows.MessageBox.Show("disc");
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
mainwind.setText(encoder.GetString(message, 0, bytesRead));
//System.Windows.MessageBox.Show(encoder.GetString(message, 0, bytesRead));
// System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
}
tcpClient.Close();
}
}