본문 바로가기

Unity

Starting TCP by Unity (3) - Practice

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.

Example creating a button

Right click on Hierarchy to create a Button.

Example creating a script

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.

Example of ButtonControl.cs

And put a simple code as above.

Put the function you made into the button

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".

Example adding extra code in Assets/Scripts/Packets.cs

As the picture above, add enum for button we will use in Assets/Scripts/Packet.cs.

Example for Assets/Scripts/ClientSend.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.)

Example for Assets/Scripts/ClientHandle.cs

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!

Example for Assets/Scripts/Client.cs

Initialize every addition we made in Assets/Scripts/Client.cs.

Example for Assets/Scripts/ButtonControl.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#.

Example for ConsoleApp1/Packet.cs

Add button enum as we did in client.

Example for ConsoleApp1/ServerHandle.cs

Traslate the data received from client in ConsoleApp1/ServerHandle.cs and use ServerSend to send received message back to client.

Example for ConsoleApp1/ServerSend.cs

Add function for sending data in ConsoleApp1/ServerSend.cs.

Example for ConsoleApp1/Server.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.

Example of result

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.