- Home /
How can I write to a socket accepted from a tcp listener?
I´m working on Unity app that can be remote-controlled via an iOS app. The Unity app has got a tcp listener, that handles the incoming data. That works fine so far.
Now I want Unity to send a response to the iOS app. I´ve tried several approaches like sending bytes to the socket, creating a NetworkStream ... Nothing worked. Here´s my unity c# code:
void Receive() {
print ("Hello world");
try{
tcp_Listener = new TcpListener(IPAddress.Parse(ip), 8082);
tcp_Listener.Start();
print("Server Start: "+ip);
}catch(Exception exc){
Debug.Log("ecx: "+exc);
}
while (mRunning) {
//check if new connections are pending, if not, be nice and sleep 100ms
if (!tcp_Listener.Pending()){
Thread.Sleep(100);
}else {
Socket ss = tcp_Listener.AcceptSocket();
byte[] tempbuffer = new byte[10000];
ss.Receive(tempbuffer); // received byte array from client
var str = System.Text.Encoding.Default.GetString(tempbuffer);
Loom.RunAsync(()=>{
Loom.QueueOnMainThread(()=>{
parse(str);
});
});
// send response
string data = "hallo";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
ss.Send(bytes);
ss.Close();
Debug.Log("sending: "+System.Text.Encoding.UTF8.GetString(bytes));
}
}
}
The string "hallo" is never written to the output.
What am I doing wrong?
Thanks very much in advance, K.
Answer by thelghome · Jul 31, 2019 at 06:07 PM
your "ss.Receive(tempbuffer); " is a blocking method. It is not able to send any response until it received message from server.
If someone still needs detailed examples, you may try FMETP STREAM | Forum It provides Streaming Demo with TCP solution, and Web browser demo with Socket.IO.
All source code are written in C# and easy to modify.
Supported: Android/iOS/Mac/PC