- Home /
TCPclient ... how to collect a responce with an unknown size?
I have a TPC server that seems to work well for my game but I am having troubles with the client side.
from what i am trying to understand. the client needs to create a buffer with a designated size to collect the responce? sometimes the incomming answers are as large as big image files and sometimes this code collects things as small as a small text responce. is there a way to use a memorystream or other technique to collect responses besides trying to use a really big buffer?
here is the code i am using. it works about half the time. Usually the game needs to repeat the same connection request a couple times to get the full file/answer.
hopefully someone can give me an idea why this is only working part of the time, or suggest some other way to simply collect any given responce from a server into a byte array?
try{
display.q = "TCP: "+Que[0].Type.ToUpper()+ Que[0].Message;
TcpClient tcp = new TcpClient ();
tcp.Connect (IP,PORT);
Stream s = tcp.GetStream();
ASCIIEncoding asen= new ASCIIEncoding();
byte[] bsend=asen.GetBytes(ServerID+"WD"+Que[0].Type.ToUpper()+ Que[0].Message);
s.Write(bsend,0,bsend.Length);
byte[] buff;
int k;
if(Que[0].Type.ToUpper() == "ITEM"){
buff = new byte[160000];
k=s.Read(buff,0,160000);
}else{buff=new byte[5000000];
k=s.Read(buff,0,5000000);}
answer = new byte[k];
for (int iii=0; iii<k; iii++) {
answer[iii] = buff[iii];}
// answer is my final byte array answer
tcp.Close();}
catch(SocketException e){
main.say(e.ErrorCode+" "+e.Message);
display.q = "TCP ERROR";}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612164721im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
StreamReader in while loop stops/freezes unity 2 Answers
How to avoid freezing UI in Tcp Socket Connection? 0 Answers
TCPClient and SslStreams in WebPlayer (C#) 0 Answers
Problems with tcpclient 0 Answers