- Home /
Question by
Providence4991 · Apr 05, 2016 at 12:58 PM ·
unity 5networkingmultiplayersocketsockets
Can we use Unitys LLAPI to establish a socket connect with a server?
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using UnityEngine.Networking;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Net;
public class WebSocketService : GenericSingleton<WebSocketService>
{
int myReliableChannelId;
int socketId;
int socketPort = 8282;
int connectionId;
int recHostId;
int recConnectionId;
int recChannelId;
const int bufferSize = 2048;
byte[] recBuffer = new byte[bufferSize];
int dataSize;
byte error;
string socketurl = "192.168.0.116/join";
void Start()
{
NetworkTransport.Init();
ConnectionConfig config = new ConnectionConfig();
myReliableChannelId = config.AddChannel(QosType.Reliable);
int maxConnections = 10;
HostTopology topology = new HostTopology(config, maxConnections);
socketId = NetworkTransport.AddHost(topology, 8080);
Debug.Log("Socket Open. SocketId is: " + socketId);
Connect();
}
public void Connect()
{
byte error;
connectionId = NetworkTransport.Connect(socketId, socketurl, socketPort, 0, out error);
Debug.Log("Connected to server. ConnectionId: " + connectionId);
Debug.Log("Error ? : " + error);
}
public void SendSocketMessage(string msg)
{
byte error;
var bytes = Encoding.UTF8.GetBytes(msg);
NetworkTransport.Send(socketId, connectionId, myReliableChannelId, bytes, bufferSize, out error);
Debug.Log("Error ? : " + error);
}
void Update()
{
NetworkEventType recNetworkEvent = NetworkTransport.Receive(out recHostId, out recConnectionId, out recChannelId, recBuffer, bufferSize, out dataSize, out error);
switch (recNetworkEvent)
{
case NetworkEventType.Nothing:
Debug.Log(" NetworkEventType.Nothing");
break;
case NetworkEventType.ConnectEvent:
Debug.Log(" NetworkEventType.ConnectEvent");
break;
case NetworkEventType.DataEvent:
Debug.Log(" NetworkEventType.DataEvent");
break;
case NetworkEventType.DisconnectEvent:
Debug.Log(" NetworkEventType.DisconnectEvent");
break;
}
}
}
am i doing this right?my socket endpoint is socketurl. is there any other way to achieve this using unitys new networking suite.
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612074225im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiplayer game using Sockets or Socket.IO? (without UNET or Photon) 6 Answers
Unity networking tutorial? 6 Answers
Chat system is not working 1 Answer
uNet Offline and Online Scenes the Same 2 Answers
Trouble syncing player model animation over network 2 Answers