I’m trying to read data from a Java service on an Android device. But Unity always refuses to connect to the TCP socket. It refuses in the editor, it refuses on Android and it refuses if I try to build for Windows. In the Editor, it says: System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it.
My code is below. It’s a adapted from an example from a Microsoft API page. uPrint
is a function I wrote to print text both in the console and in a GUIText.
The code is called with:
Connect("127.0.0.1", "Hello!");
I’ve tried "0.0.0.0"
and "localhost"
for the host name. It didn’t work.
I haven’t found a way to get at which line exactly the error occurs. Even removing the try/catch blocks does not give me the exact line where it fails.
The Windows firewall allows the Unity editor full access to the network.
void Connect(string server, string message) {
try {
// Create a TcpClient.
// Note, for this client to work you need to have a TcpServer
// connected to the same address as specified by the server, port
// combination.
int port = 15219;
TcpClient client = new TcpClient(server, port);
// Translate the passed message into ASCII and store it as a Byte array.
byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream(); // GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
// stream.Write(data, 0, data.Length);
uPrint(string.Format("Sent: {0}", message));
// Receive the TcpServer.response.
// Buffer to store the response bytes.
data = new Byte[256];
// String to store the response ASCII representation.
string responseData = string.Empty;
// Read the first batch of the TcpServer response bytes.
int bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
uPrint(string.Format("Received: {0}", responseData));
// Close everything.
stream.Close();
client.Close();
}
catch (ArgumentNullException e) {
uPrint(string.Format("ArgumentNullException: {0}", e));
}
catch (SocketException e) {
uPrint(string.Format("SocketException: {0}", e));
}
}