📖 Scenario: You are building a simple client-server system in Unity to understand how data can be sent from a client to a server and back.Imagine a game where the client sends a player's name to the server, and the server responds with a welcome message.
🎯 Goal: Create a basic client-server communication in Unity using C# scripts. The client will send a player's name to the server, and the server will send back a welcome message. You will build this step-by-step.
📋 What You'll Learn
Create a server script that can receive a player's name
Create a client script that sends the player's name to the server
Implement simple message passing between client and server
Display the server's welcome message on the client
💡 Why This Matters
🌍 Real World
Client-server architecture is used in multiplayer games and networked applications to allow communication between players and game servers.
💼 Career
Understanding client-server communication is essential for game developers working on online multiplayer games or networked applications.
Progress0 / 4 steps
1
Create the Server script with a method to receive player name
Create a C# script called Server with a public method ReceivePlayerName that takes a string parameter called playerName. Inside the method, create a string variable called welcomeMessage and set it to the value $"Welcome, {playerName}!".
Unity
Hint
Define a public method that returns a string. Use string interpolation to create the welcome message.
2
Create the Client script with a playerName variable
Create a C# script called Client with a public string variable called playerName and set it to "Alex".
Unity
Hint
Declare a public string variable named playerName and assign it the value "Alex".
3
Add a method in Client to send playerName to Server and get response
In the Client class, add a public method called SendNameToServer that takes a Server object as a parameter. Inside this method, call the server's ReceivePlayerName method with playerName and store the result in a string variable called response.
Unity
Hint
Define a method that takes a Server object, calls its ReceivePlayerName method with playerName, and returns the response.
4
Print the server's welcome message in a Unity Start method
In the Client class, add a Start method. Inside it, create a new Server object, call SendNameToServer with this server, and print the returned welcome message using UnityEngine.Debug.Log.
Unity
Hint
Use Debug.Log inside the Start method to print the welcome message.
Practice
(1/5)
1. In Unity's client-server architecture, what is the main role of the client?
easy
A. Send requests to the server and receive responses
B. Store all game data permanently
C. Control the server hardware
D. Manage other clients directly
Solution
Step 1: Understand client role in client-server
The client initiates communication by sending requests to the server.
Step 2: Understand server response
The server processes requests and sends back responses to the client.
Final Answer:
Send requests to the server and receive responses -> Option A
2. Which of the following is the correct way to create a TcpClient in Unity C#?
easy
A. TcpClient client = TcpClient("127.0.0.1", 8080);
B. TcpClient client = new TcpClient.connectTo("127.0.0.1", 8080);
C. TcpClient client = new TcpClient.connect("127.0.0.1", 8080);
D. TcpClient client = new TcpClient("127.0.0.1", 8080);
Solution
Step 1: Recall TcpClient constructor syntax
In C#, creating a new TcpClient requires the 'new' keyword and constructor with IP and port.
Step 2: Check each option's syntax
Only TcpClient client = new TcpClient("127.0.0.1", 8080); uses 'new TcpClient("127.0.0.1", 8080);' correctly.
Final Answer:
TcpClient client = new TcpClient("127.0.0.1", 8080); -> Option D
Quick Check:
Use 'new' keyword with constructor [OK]
Hint: Always use 'new' to create objects in C# [OK]
Common Mistakes:
Omitting 'new' keyword
Using incorrect method names like connect or connectTo
Wrong constructor call syntax
3. What will the following Unity C# code output if the server sends back the string "Hello Client"?
using System;
using System.Net.Sockets;
using System.Text;
TcpClient client = new TcpClient("127.0.0.1", 9000);
NetworkStream stream = client.GetStream();
byte[] data = new byte[256];
int bytes = stream.Read(data, 0, data.Length);
string response = Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine(response);
medium
A. System.Byte[]
B. Hello Client
C. null
D. Exception thrown
Solution
Step 1: Understand data reading from NetworkStream
The code reads bytes from the stream into a byte array and counts bytes read.
Step 2: Convert bytes to string
It converts the bytes read to a string using ASCII encoding, which matches the server's sent string.
Final Answer:
Hello Client -> Option B
Quick Check:
Read bytes + decode = server message [OK]
Hint: Decode bytes read from stream to get server message [OK]
Common Mistakes:
Printing byte array directly instead of decoding
Ignoring number of bytes read
Assuming null if no data
4. Identify the error in this Unity C# client code snippet:
B. Calling stream.Close() before client.Close() causes error
C. TcpClient must be created with IP and port in constructor
D. No error; code is correct
Solution
Step 1: Review TcpClient creation and connection
Creating TcpClient with default constructor and then calling Connect is valid.
Step 2: Check for error handling
Network operations can fail; missing try-catch means exceptions are unhandled.
Final Answer:
Missing try-catch block for network exceptions -> Option A
Quick Check:
Always handle network exceptions [OK]
Hint: Always wrap network calls in try-catch [OK]
Common Mistakes:
Assuming stream.Close() before client.Close() is wrong
Thinking TcpClient must have IP in constructor
Ignoring exception handling
5. You want to build a Unity client that connects to a server and sends a player's score only if it is above 1000. Which code snippet correctly implements this logic using TcpClient and NetworkStream?
hard
A. if(score > 1000) {
TcpClient client = new TcpClient("server.com");
NetworkStream stream = client.GetStream();
byte[] data = Encoding.ASCII.GetBytes(score.ToString());
stream.Write(data, 0, data.Length);
stream.Close();
client.Close();
}
B. TcpClient client = new TcpClient("server.com", 5000);
NetworkStream stream = client.GetStream();
if(score > 1000) {
byte[] data = Encoding.ASCII.GetBytes(score.ToString());
stream.Write(data, 0, data.Length);
}
stream.Close();
client.Close();
C. TcpClient client = new TcpClient();
if(score > 1000) {
client.Connect("server.com", 5000);
NetworkStream stream = client.GetStream();
byte[] data = Encoding.ASCII.GetBytes(score.ToString());
stream.Write(data, 0, data.Length);
stream.Close();
client.Close();
}
D. if(score > 1000) {
TcpClient client = new TcpClient();
client.Connect("server.com", 5000);
NetworkStream stream = client.GetStream();
byte[] data = Encoding.ASCII.GetBytes(score);
stream.Write(data, 0, data.Length);
stream.Close();
client.Close();
}
Solution
Step 1: Check conditional connection and sending
TcpClient client = new TcpClient();
if(score > 1000) {
client.Connect("server.com", 5000);
NetworkStream stream = client.GetStream();
byte[] data = Encoding.ASCII.GetBytes(score.ToString());
stream.Write(data, 0, data.Length);
stream.Close();
client.Close();
} creates TcpClient without parameters, connects only if score > 1000, then sends data.
Step 2: Verify data conversion and method calls
Converts score to string before encoding to bytes, uses correct Connect() and stream methods.
Final Answer:
new TcpClient(); client.Connect() inside if(score > 1000) -> Option C
Quick Check:
Connect and send inside if condition [OK]
Hint: Connect and send only inside the if block [OK]
Common Mistakes:
Sending data without converting score to string
Connecting outside the if condition
Using score directly as bytes without encoding
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.