- Home /
Crash using Sockets
Hi guys, just trying to use sockets in my app and unity crashes when declaring a new socket: Just this line crashes unity entirely, even when put on a coroutine
Socket soc = listener.AcceptSocket();
What I'm missing?
Here is full server code:
using UnityEngine;
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
public class ReceiveStuff : MonoBehaviour {
TcpListener listener;
// Use this for initialization
void Start ()
{
listener = new TcpListener(2333);
listener.Start();
Debug.Log("Server Iniciado");
StartCoroutine("listen");
}
IEnumerator listen()
{
while(true)
{
Socket soc = listener.AcceptSocket();
Debug.Log("Conectados" + soc.RemoteEndPoint.ToString());
try
{
Stream s = new NetworkStream(soc);
StreamReader sr = new StreamReader(s);
StreamWriter sw = new StreamWriter(s);
sw.AutoFlush = true;
while(true)
{
string name = sr.ReadLine();
if(name == "" || name == null)
{
}
else
{
Debug.Log("RECEBIDO: " + name);
}
}
s.Close();
}
catch(Exception e)
{
Debug.Log("EXCEPTION: " + e.Message);
}
soc.Close();
yield return null;
}
}
Is there anything in the log? $$anonymous$$aybe you are just missing some dlls. Which platform are you running on? $$anonymous$$ono has different capabilities on different platforms.
Nothing in the log, unity crashes instantly when play is hit as if it has encountered an infinite loop.
Answer by robin-theilade · Sep 18, 2012 at 07:34 PM
The AcceptSocket method is blocking which may cause the behavior you are seeing.
Try using the BeginAcceptSocket instead. http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.beginacceptsocket(v=vs.90).aspx
Thanks robin, later on I discovered that but my problem continues. You seems to know you stuff, hope to see you helping in my new question here:
http://answers.unity3d.com/questions/319560/how-to-do-a-tcp-server.html
I have not tried your solution still.