Not too much to say but I made a project long ago from a tutorial which I’d like to use for my unity project ![]()
It works fine on its own but I am not sure I fully understand what I am doing nor can I find the problem myself.
Unity keeps on freeze and I have no idea why here is the code I use:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using UnityEngine;
class Client : MonoBehaviour {
public Socket master;
public string name;
public string id;
public string Msg;
public void setName(string inp){name = inp;}
public void setMsg(string inp){Msg = inp;}
public void sendChat(){
Packet p = new Packet(Packet.PacketType.chat, id);
p.Gdata.Add(name);
p.Gdata.Add(Msg);
master.Send(p.toBytes());
}
void Start(){
master = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
string ip = Settings.ipAddres;
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ip), Settings.port);
try
{
Debug.Log("Connected");
master.Connect(ipe);
}
catch(Exception e)
{
Debug.LogError("Could not connect to server");
Debug.LogError (e.Message);
}
}
void FixedUpdate(){
byte[] buffer = new byte[master.SendBufferSize];
int readBytes = master.Receive(buffer);
if (readBytes > 0)
{
DataManager (new Packet (buffer));
}
}
void DataManager(Packet p){
switch (p.packetType) {
case Packet.PacketType.Registration:
Debug.Log("Connected to Server!");
id = p.Gdata[0];
break;
case Packet.PacketType.chat:
Debug.Log(p.Gdata[0] + ": " + p.Gdata[1]);
break;
}
}
}
Original Client code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServerData;
using System.Net;
using System.IO;
using System.Net.Sockets;
using System.Threading;
namespace client
{
class Program
{
public static Socket master;
public static string name;
public static string id;
static void Main(string[] args)
{
Console.WriteLine("Enter Your Name: ");
name = Console.ReadLine();
A: Console.Clear();
string ip = "172.20.10.3";
master = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(ip), 4242 );
try
{
master.Connect(ipe);
}
catch
{
Console.WriteLine("Could not connect to server");
Thread.Sleep(1000);
goto A;
}
Thread t = new Thread(data_IN);
t.Start();
for(;;)
{
Console.Write("::>");
string input = Console.ReadLine();
Packet p = new Packet(PacketType.chat, id);
p.Gdata.Add(name);
p.Gdata.Add(input);
master.Send(p.toBytes());
}
}
static void data_IN()
{
byte[] buffer;
int readBytes;
for(;;)
{
try
{
buffer = new byte[master.SendBufferSize];
readBytes = master.Receive(buffer);
if (readBytes > 0)
{
DataManager(new Packet(buffer));
}
}
catch (SocketException ex)
{
Console.WriteLine("Server Lost!");
Console.ReadLine();
Environment.Exit(0);
}
}
}
static void DataManager(Packet p)
{
switch (p.packetType)
{
case PacketType.Registration:
Console.WriteLine("Connected to Server!");
id = p.Gdata[0];
break;
case PacketType.chat:
Console.WriteLine(p.Gdata[0] + ": " + p.Gdata[1]);
break;
}
}
}
}
Everything else:
Server
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServerData;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Net;
namespace Server
{
class Server
{
static Socket listenerSocket;
static List<ClientData> _clients;
static void Main(string[] args)
{
Console.WriteLine("Starting Server...");
listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_clients = new List<ClientData>();
IPEndPoint ip = new IPEndPoint(IPAddress.Parse(Packet.getIp4Address()), 4242);
listenerSocket.Bind(ip);
Thread listenThread = new Thread(ListenThread);
listenThread.Start();
Console.WriteLine("Success... Listening IP: " + Packet.getIp4Address() + ":4242");
}
static void ListenThread()
{
for (; ; )
{
listenerSocket.Listen(0);
_clients.Add(new ClientData(listenerSocket.Accept()));
}
}
public static void Data_IN(object cSocket)
{
Socket clientSocket = (Socket)cSocket;
byte[] Buffer;
int readBytes;
for (;;)
{
try
{
Buffer = new byte[clientSocket.SendBufferSize];
readBytes = clientSocket.Receive(Buffer); // https://www.youtube.com/watch?v=X66hFZG5p3A
if (readBytes > 0)
{
Packet p = new Packet(Buffer);
dataManager(p);
}
}
catch (SocketException ex)
{
Console.WriteLine("Client Disconnected.");
}
}
}
public static void dataManager(Packet p)
{
switch (p.packetType)
{
case PacketType.chat:
foreach (ClientData c in _clients)
{
c.clientSocket.Send(p.toBytes());
}
break;
}
}
class ClientData
{
public Socket clientSocket;
public Thread clientThread;
public string id;
public ClientData()
{
id = Guid.NewGuid().ToString();
clientThread = new Thread(Server.Data_IN);
clientThread.Start(clientSocket);
sendRegistrationPacket();
}
public ClientData(Socket clientSocket)
{
this.clientSocket = clientSocket;
id = Guid.NewGuid().ToString();
clientThread = new Thread(Server.Data_IN);
clientThread.Start(clientSocket);
sendRegistrationPacket();
}
public void sendRegistrationPacket()
{
Packet p = new Packet(PacketType.Registration, "server");
p.Gdata.Add(id);
clientSocket.Send(p.toBytes());
}
}
}
}
Packet
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Net;
namespace ServerData
{
[Serializable]
public class Packet
{
public List<string> Gdata;
public int packetInt;
public bool packetBool;
public string senderId;
public PacketType packetType;
public Packet(PacketType type, string senderId)
{
Gdata = new List<string>();
this.senderId = senderId;
this.packetType = type;
}
public Packet(byte[] packetBytes)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream(packetBytes);
Packet p = (Packet)bf.Deserialize(ms);
Console.WriteLine(p.packetType);
ms.Close();
Gdata = p.Gdata;
packetInt = p.packetInt;
packetBool = p.packetBool;
senderId = p.senderId;
packetType = p.packetType;
}
public byte[] toBytes()
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, this);
byte[] bytes = ms.ToArray();
ms.Close();
return bytes;
}
public static string getIp4Address()
{
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress i in ips)
{
if (i.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
return i.ToString();
}
}
return "127.0.0.1";
}
}
public enum PacketType
{
Registration,
chat
}
}