why I received this: received string , when I send this? sended string
Cod of client app:
try
{
tcpclient.Connect("127.0.0.1", 80);
String str = "LOG" + Login.Text + "$" + hasło.Text;
Stream stm = tcpclient.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] buffer = asen.GetBytes(str);
stm.Write(buffer, 0, buffer.Length);
Cod of host:
try
{
string msg = "";
Socket socket = Listerner.AcceptSocket();
ASCIIEncoding asen = new ASCIIEncoding();
int x = socket.ReceiveBufferSize;
byte[] buffor = new byte[x];
int data = socket.Receive(buffor);
string wiadomość = Encoding.ASCII.GetString(buffor);
This is because your buffor
variable at the host has a fixed size and thus Encoding.ASCII.GetString
will try to convert the complete byte array back to a string, regardless how many bytes were actually received.
socket.Receive
returns the number of bytes that were actually received. Use this information to restore the string:
int bytesReceived = socket.Receive(buffor);
string wiadomość = Encoding.ASCII.GetString(buffor, 0, bytesReceived);
See Encoding.ASCII.GetString and Socket.Receive for reference.
Now it should work for your tiny example. But be aware that you might receive more bytes than your buffer can take at once. So you have to do something like:
string messageReceived = "";
int bytesReceived = 0;
do
{
bytesReceived = socket.Receive(buffor)
messageReceived += Encoding.ASCII.GetString(buffor, 0, bytesReceived);
} while(bytesReceived >= buffor.Length)
// now messageReceived should contain the whole text
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.