In this time, we will send and receive data between Server and Client.
Now let's try with clicking a button info to send and receive.
Right click on Hierarchy to create a Button.
And then right click again in Assets/Scripts to create a script named as ButtonControl.
Then put the script into an empty object named ButtonControl.
And put a simple code as above.
Follow the steps I wrote to put the function we created in ButtonControl script into the On Click function part.
Now let's start the project to see if the button creates a log "Button is clicked".
As the picture above, add enum for button we will use in Assets/Scripts/Packet.cs.
Add "ButtonClick" as above picture in Assets/Scripts/ClientSend.cs.
(Reason why we do it like above is because when you actually send and receive data throuch socket, you cannot send and receive it as string shape so we change it into bytes and save them into a packet to send, and when you receive it, make the original string shape from bytes.)
In Assets/Scripts/ClientHandle.cs, this is a part changing bytes into string.
Let's create this ahead so we don't have to come back here!
Initialize every addition we made in Assets/Scripts/Client.cs.
Come back to ButtonControl.cs and send info through a button click.
Now the client side is ready.
Let's deal with server we made with C#.
Add button enum as we did in client.
Traslate the data received from client in ConsoleApp1/ServerHandle.cs and use ServerSend to send received message back to client.
Add function for sending data in ConsoleApp1/ServerSend.cs.
Insitialize every addition for enum and ServerHandle in ConsoleApp1/Server.cs.
Now we are all ready and it's time to check.
Start the server first then start Client to connect.
Click on the button.
We can see it's sharing data successfully on Server(right picture) and Client(Left picture)!
This is the way to send and receive data through TCP socket.
'Unity' 카테고리의 다른 글
Unity Error without specific reason - it works but has red lines on visual studio files (0) | 2023.01.24 |
---|---|
A method as a parameter - how to use Delegate (0) | 2023.01.24 |
Starting TCP by Unity (2) - Client (0) | 2022.10.26 |
Starting TCP by Unity (1) - Server (0) | 2022.10.26 |
Unity tips for Beginner (2) - Dealing with static string and int (0) | 2022.10.26 |