T
Tomas Machala
Hi, I'm trying to make an application communicating over TCP/IP. It should do only one thing - write received data to console and terminate itself when "exit" received. Problem is that if I send some string to this application, it'll receive that string and many unwanted "new line" characters on its end.
Examle:
If I send
"some_string"
application display
"some_string
"
I can't find the reason why it does so. Here's my code:
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace NetPokus
{
class NetPokus
{
[STAThread]
static void Main(string[] args)
{
string recv;
Odpovedi odp;
try
{
odp = new Odpovedi();
}
catch (SocketException ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
return;
}
while (true)
{
odp.Write("Waiting for command\n");
recv = odp.Read();
if (recv == "exit")
{
break;
}
else
{
Console.Write(recv);
}
}
odp.Close();
}
}
public class Odpovedi
{
TcpClient client;
NetworkStream nstr;
byte[] received;
byte[] toSend;
public Odpovedi()
{
client = new TcpClient("127.0.0.1", 1234);
nstr = client.GetStream();
}
public void Write(string msg)
{
toSend = Encoding.ASCII.GetBytes(msg);
nstr.Write(toSend, 0, toSend.Length);
}
public string Read()
{
received = new byte[client.ReceiveBufferSize];
nstr.Read(received, 0, client.ReceiveBufferSize);
return Encoding.ASCII.GetString(received);
}
public void Close()
{
client.Close();
}
}
}
Examle:
If I send
"some_string"
application display
"some_string
"
I can't find the reason why it does so. Here's my code:
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace NetPokus
{
class NetPokus
{
[STAThread]
static void Main(string[] args)
{
string recv;
Odpovedi odp;
try
{
odp = new Odpovedi();
}
catch (SocketException ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
return;
}
while (true)
{
odp.Write("Waiting for command\n");
recv = odp.Read();
if (recv == "exit")
{
break;
}
else
{
Console.Write(recv);
}
}
odp.Close();
}
}
public class Odpovedi
{
TcpClient client;
NetworkStream nstr;
byte[] received;
byte[] toSend;
public Odpovedi()
{
client = new TcpClient("127.0.0.1", 1234);
nstr = client.GetStream();
}
public void Write(string msg)
{
toSend = Encoding.ASCII.GetBytes(msg);
nstr.Write(toSend, 0, toSend.Length);
}
public string Read()
{
received = new byte[client.ReceiveBufferSize];
nstr.Read(received, 0, client.ReceiveBufferSize);
return Encoding.ASCII.GetString(received);
}
public void Close()
{
client.Close();
}
}
}