Unity_ Small function implementation (client mutual communication function)

Source: Internet
Author: User

Server-side: New project in VS, for server Building

Using System;
Using System.Collections.Generic;
Using System.Net.Sockets;
Using System.Net;
Using System.Text;
Using System.Threading;

Namespace Chat_server
{

Class Client
{
Private Socket Clientsocket;
Private Thread t;
Private byte[] data = new byte[1024];//receive the container

static list<client> clientlist = new list<client> ();

static void Main (string[] args)
{
Socket tcpserver = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);
Tcpserver.bind (New IPEndPoint (Ipaddress.parse ("192.168.43.231"), 7788));
Tcpserver.listen (100);

Console.WriteLine ("Server is runing");

dead loop: Resolves a problem that can only receive one client
while (true)
{
Socket clientsocket = tcpserver.accept ();//Pause, execute the following code when there is a client connection
Console.WriteLine ("There is a client connected");
Client client = new Client (clientsocket);
Clientlist.add (client);
}

}
If the connection succeeds, true for success
public bool Connected
{
get {return clientsocket.connected;}
}
Public Client (Socket s)
{
Clientsocket = s;
Initiates a thread processing client's data reception
t = new Thread (ReceiveMessage);
T.start ();
}
Receive messages sent from the client
private void ReceiveMessage ()
{
Always receive client-side data
while (true)
{
Determine if the socket connection is disconnected before receiving the data, and wait 10 milliseconds for the response. When disconnecting:
if (Clientsocket.poll (ten, Selectmode.selectread))
{
Clientsocket.close ();
break;//jumping out of the loop to terminate the execution of a thread
}

Receiving messages
int length = clientsocket.receive (data);
String message = Encoding.UTF8.GetString (data, 0, length);

Broadcastmessage (message);
Console.WriteLine ("Received message:" + message);
}
}
The server sends a message to the client
public void SendMessage (String message)
{
byte[] data = Encoding.UTF8.GetBytes (message);
Clientsocket.send (data);
}
Server-side broadcast messages to clients
public static void Broadcastmessage (String message)
{
var notconnectedlist = new list<client> ();
foreach (var client in clientlist)
{
if (client. Connected)//Connect successful broadcast messages
Client. SendMessage (message);
else//The failed connection is stored in another generic collection, which is easy to remove later
{
Notconnectedlist.add (client);
}
}
To remove an disconnected client
foreach (var temp in notconnectedlist)
{
Clientlist.remove (temp);
}
}

}
}

Unity Client:

Using Unityengine;
Using System.Collections;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
Using System.Threading;

public class Chatmanager:monobehaviour
{
public string ipaddress = "192.168.43.231";
public int port = 7788;

Public Uiinput TextInput;
Public UILabel Chatlabel;

Private Socket Clientsocket;
Private Thread t;

Private byte[] data = new byte[1024];//container
private String message = "";//messages received from container

void Start () {
Connecttoserver ();
}
void Update () {
if (message! = NULL && Message! = "")
{
Chatlabel.text + = "\ n" + message;
message = "";//Clear messages
}
}
void Connecttoserver ()
{
Clientsocket = new Socket (Addressfamily.internetwork,sockettype.stream, protocoltype.tcp);
Establish a connection with the server side
Clientsocket.connect (New IPEndPoint (Ipaddress.parse (IPAddress), port));

Create a new thread to receive the message
t = new Thread (ReceiveMessage);
T.start ();
}
Receiving messages
void ReceiveMessage ()
{
while (true)
{
if (clientsocket.connected = = False)
Break
int length = clientsocket.receive (data);
Message = Encoding.UTF8.GetString (data, 0, length);

}
}
Send Message
void SendMessage (String message)
{
byte[] data = Encoding.UTF8.GetBytes (message);
Clientsocket.send (data);
}
Send button
public void Onsendbuttonclick ()
{
String value = Textinput.value;
SendMessage (value);
Textinput.value = "";
}

void OnDestroy ()
{
Clientsocket.shutdown (Socketshutdown.both);

Clientsocket.close ();//close connection
}
}
Note: We use threads on both the client and server side, and the thread is designed to speed up the library and improve performance. Server-side, use threads to receive data, and clients use threads to send data.

Unity_ Small function implementation (client mutual communication function)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.