- Home /
How to send/receive float values from other online players
I am relatively new in developing online games, so I don't know too much details on the proper methods of setting things up except for the basics. The only issue I've found myself having is being able to send values to other players. I understand how you can make a player lose health when they get hit by a bullet. I want to know how I could share values of players power of attack and then compare that attack with another's. If someone could refer/type just a simple script js/c# of how a float value can be shared with another player online it be extremely helpful, because I've been looking for months and i've yet to find exactly what i'm looking for.
Answer by efeguclu · Jul 06, 2017 at 12:36 AM
CricketNew10
You are In your Lucky Day I'm going to write a script I'm going to use Net.Sockets and NetStreams... First, Create A Script called Server.cs And attach it to an empty gameObject.. Copy Paste this codes into that:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net.Sockets;
using System;
using System.Net;
using System.IO;
public class Server : MonoBehaviour {
#region variables
public int port = 6321;
public static Server Instance { set; get; }
private List<ServerClient> clients;
public List<IPAddress> Hosts;
private List<ServerClient> disconnectList;
private TcpListener server;
private bool isServerStarted;
#endregion
private void Start() {
Instance = this;
}
public void Init() {
DontDestroyOnLoad(gameObject);
clients = new List<ServerClient>();
disconnectList = new List<ServerClient>();
try
{
server = new TcpListener(IPAddress.Any, port);
server.Start();
StartListening();
isServerStarted = true;
}
catch (Exception e)
{
Debug.Log("Server Açılamadı : " + e.Message);
}
}
private void Update() {
if (!isServerStarted)
return;
foreach (ServerClient c in clients)
{
if (!IsConnected(c.tcp))
{
c.tcp.Close();
disconnectList.Add(c);
continue;
}
else {
NetworkStream s = c.tcp.GetStream();
if (s.DataAvailable) {
StreamReader okuyucu = new StreamReader(s, true);
string data = okuyucu.ReadLine();
if (data != null)
OnIncomingData(c, data);
}
}
}
}
private void StartListening()
{
server.BeginAcceptTcpClient(AcceptTcpClient,server);
}
private void AcceptTcpClient(IAsyncResult ar)
{
TcpListener listener = (TcpListener)ar.AsyncState;
string herkes = "";
foreach (ServerClient i in clients) {
herkes += i.clientName + "|";
}
ServerClient sc = new ServerClient(listener.EndAcceptTcpClient(ar));
clients.Add(sc);
StartListening();
Broadcast("SCON|" + herkes,clients[clients.Count-1]);
Debug.Log("Added to clients : " + sc.clientName);
}
private bool IsConnected(TcpClient tcp)
{
try {
if (tcp != null && tcp.Client != null && tcp.Client.Connected)
{
if (tcp.Client.Poll(0, SelectMode.SelectRead))
return !(tcp.Client.Receive(new byte[1], SocketFlags.Peek) == 0);
return true;
}
else {
return false;
}
}
catch
{
return false;
}
}
#region DataSendGet
private void Broadcast(string data, List<ServerClient> serverClients)
{
foreach (ServerClient sc in serverClients)
{
try {
StreamWriter yazici = new StreamWriter(sc.tcp.GetStream());
yazici.WriteLine(data);
yazici.Flush();
Debug.Log(sc.clientName);
} catch(Exception e){
Debug.Log(e.Message);
}
}
}
private void Broadcast(string data, ServerClient serverClient)
{
List<ServerClient> sc = new List<ServerClient>() { serverClient };
Broadcast(data, sc);
}
private void OnIncomingData(ServerClient c, string data)
{
Debug.Log("Server:" + data);
string[] datalar = data.Split('|');
switch (datalar[0])
{
case "CCON":
c.clientName = datalar[1];
c.isHost = (datalar[2] == "0") ? false : true;
if (!clients.Contains(c))
clients.Add(c);
Broadcast("SCNN|" + c.clientName, clients);
break;
case "CMSG":
Broadcast("SMSG|" + c.clientName + "|" + datalar[1], clients);
break;
}
}
#endregion
}
public class ServerClient
{
public string clientName;
public TcpClient tcp;
public bool isHost;
public ServerClient(TcpClient tcp)
{
this.tcp = tcp;
}
}
After that Create a script called Client.cs And Attach it to an Empty gameObject.. Copy Paste this codes into client.cs:
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Net.Sockets;
using System;
using UnityEngine.UI;
public class Client : MonoBehaviour {
#region variables
public string ClientAD;
public bool isHost;
private bool isConnected;
private TcpClient tcpclient;
private StreamReader okuyucu;
private StreamWriter gonderici;
public NetworkStream netstream;
public List<Cliente> users = new List<Cliente>();
#endregion
private void Start() {
DontDestroyOnLoad(gameObject);
}
public bool ConnectToServer(string host, int port)
{
if (isConnected)
return false;
try
{
tcpclient = new TcpClient(host,port);
netstream = tcpclient.GetStream();
gonderici = new StreamWriter(netstream);
okuyucu = new StreamReader(netstream);
isConnected = true;
}
catch (Exception e)
{
Debug.Log("Baglantı Hatası : " + e.Message);
}
return isConnected;
}
private void Update() {
if (isConnected)
{
if (netstream.DataAvailable)
{
string data = okuyucu.ReadLine();
if (data != null)
{
OnIncomingData(data);
}
}
}
}
public void Gonder(string data) {
if (!isConnected)
return;
gonderici.WriteLine(data);
gonderici.Flush();
}
private void OnIncomingData(string data) {
Debug.Log("Client:" + data);
// EXAMPLE : SMSG|AhmetMehmetVeli|15.0f
string[] datalar = data.Split('|');
switch (datalar[0])
{
case "SCON":
for (int i = 1; i < datalar.Length - 1; i++)
{
UserConnected(datalar[i], false);
}
Gonder("CCON|"+ClientAD + "|" + ((isHost)?1:0).ToString());
break;
case "SCNN":
UserConnected(datalar[1], false);
break;
case "SMSG":
string message = datalar[2];
float msgFloat = float.Parse(message);
ChatManager.Instance.GetChatMessage(msgFloat);
break;
}
}
private void UserConnected(string name, bool host) {
Cliente newclient = new Cliente();
newclient.clientname = name;
newclient.isHost = host;
users.Add(newclient);
}
private void OnApplicationQuit() {
CloseSocket();
}
private void OnDisable() {
CloseSocket();
}
private void CloseSocket() {
if (!isConnected)
return;
gonderici.Close();
okuyucu.Close();
tcpclient.Close();
isConnected = false;
}
}
public class Cliente
{
public string clientname;
public bool isHost;
}
Now create scene for connecting and u are going to use this public voids.. If you are going to be host and create your server you are going to use HostButton() if you are going to connect to existing host you are going to use ConnectToServer()
public GameObject serverPrefab, clientPrefab;
public void ConnectToServer() {
try
{
Client c = Instantiate(clientPrefab).GetComponent<Client>();
c.ClientAD = GameObject.Find("nameField").GetComponent<InputField>().text;
c.isHost = false;
if (c.ClientAD == "")
c.ClientAD = "Stranger";
//Under this line you see 127.0.0.1 that is ip you are going to connect and 6321 is the port
make sure port is same with host's port...
c.ConnectToServer("127.0.0.1", 6321);
}
catch (Exception e)
{
Debug.Log(e.Message);
}
}
public void HostButton() {
try {
Server s = Instantiate(serverPrefab).GetComponent<Server>();
s.Init();
Client c = Instantiate(clientPrefab).GetComponent<Client>();
c.ClientAD = GameObject.Find("nameField").GetComponent<InputField>().text;
c.isHost = true;
if (c.ClientAD == "")
c.ClientAD = "Admin";
// this line below you are seeing an ip that is localhost and means your ip you can create
host wherever you want and 6321 is port
c.ConnectToServer("127.0.0.1", 6321);
Debug.Log("Created Server at port: 6321");
}
catch (Exception e) {
Debug.Log(e.Message);
}
}
And finally you are going to take and send values with these lines :
public static ChatManager Instance { set; get; }
void Start () {
Instance = this;
}
public void SendMessage() {
/* this is you InputField that you are going to write your message if you don't created(You don't have) you can use custom string like : string s = "bla bla bla"*/
InputField ifield = GameObject.Find("messageField").GetComponent<InputField>();
if (ifield.text == "")
return;
string msg = "CMSG|" + ifield.text;
Client client = FindObjectOfType<Client>();
client.Gonder(msg);
ifield.text = "";
}
public void GetChatMessage(float value)
{
// value = the value that you got from another onlines
}
Probably because the stuff you posted is meant for 2-3 players, not 50-100k :)
no it's probaby not because there is a server component if you open in server machine and everyone connects to it. so you could be 100k players if you want
Answer by Vollmondum · Jul 04, 2017 at 11:05 AM
You are looking for a purchasing of a server computer with Windows Server installed and constantly running to receive/send data from/to players. Best servers tutorial And since you're saying you're new to online, let it go till have extra $5.000 and extra 1-2 years for learning MySQL to be run on that server.MySQL learning
Another thing is fake online. Create a list of 1000-10000 names and let people think they are online.
Have fun :)
Answer by ctalystnetwork · Jul 05, 2017 at 10:19 PM
Multiplayer poses a lot of questions and issues to address.
The Load: How many players are you expecting?
The Frequency: How often will you be updating the position?
The latency: Where in the world will you servers be?
Performance: How fast can the server get and send the information
After figuring out what you need here you have to set up a server and set it all up. Now the question that this brings up is is it worth it? Your development costs and learning curve will delay the release of your game and set you back some money. Altho there are other services out there that offer to take care of a lot of the dev for you. Take a look at Amazon, or Unitys Multiplayer
With any set up you will have an operating cost.
Now for my shameless self promotion: take a look at ctalyst to help offset these costs! We're even giving a $100 free for new developers!
Your answer
![](https://koobas.hobune.stream/wayback/20220612125455im_/https://answers.unity.com/themes/thub/images/avi.jpg)