Reputation: 907
I'm wanting my unity application to act like a server and read in some TCP strings that are being sent to it. However, the code I have at the moment seems to freeze my program and I have to go into the task manager to quit out.
Can someone with more knowledge of TCP connections take a look over my code to see what I'm doing wrong and what the cause of this is?
My entire class is as follows:
public class TCP : MonoBehaviour
{
string ip_address = "127.0.0.1";
int port = 22;
// Use this for initialization
void Start ()
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var ipAddress = IPAddress.Parse(ip_address);
EndPoint ep = new IPEndPoint(ipAddress, port);
socket.Connect(ep);
while(socket.Connected)
{
byte[] bytes = new byte[256];
int i = socket.Receive(bytes);
Debug.Log(Encoding.UTF8.GetString(bytes));
}
}
// Update is called once per frame
void Update () {
}
}
I have one request, my knowledge of this subject is very limited, if you make a suggestion to how I can fix it could you please either put up a code example so I can see how to implement it or link to something I can read to get more information?
Upvotes: 0
Views: 3475
Reputation: 22038
The socket.Receive(bytes)
will block the current thread. You could look at async tasks or asynchronous sockets.
byte[] buffer = new byte[count];
socket.BeginReceive(buffer, 0, count, SocketFlags.None, (asyncResult) =>
{
int bytesRead = socket.EndReceive(asyncResult);
if(bytesRead == 0)
{
// disconnected.
}
}
here is an example: http://csharp.vanlangen.biz/network-programming/async-sockets/asyncsocketreader/
The example will read the given amount of bytes, then calls the action you passed as parameter.
Upvotes: 0
Reputation: 3333
socket.Receive(bytes);
is a blocking call, meaning it will put thread to sleep until it recieves something. You should either move the call to separate thread together with the outer loop (so it no longer blocks your main thread) or use an async version BeginRecieve and replace loop with async model (check the link for an example)
Upvotes: 1