[Unity3d self-learning Record] socket chat room on unity3d Network

Source: Internet
Author: User
Tags getstream sendmsg

First, create a server program. Then, use the console program of.

The Code is as follows:

Using system; using system. collections. generic; using system. LINQ; using system. text; using system. net. sockets; namespace socketserver {class program {const int Port = 20000; // set the connection port Static void main (string [] ARGs) {// initialize serverip system. net. IPaddress socketip = system. net. IPaddress. parse ("127.0.0.1"); // create the TCP listener tcplistener listener = new tcplistener (socketip, Port); listener. start (); // display the server Start information console. writeline ("the service is being enabled... \ n "); // cyclically accept the client connection request while (true) {chatclient Client client = new chatclient (listener. accepttcpclient (); // displays the IP address and port console used to connect to the client. writeline (client. _ clientip + "?... \ N ");}}}}

Using system; using system. collections. generic; using system. LINQ; using system. text; using system. collections; using system. net. sockets; namespace socketserver {class chatclient {public static hashtable allclients = new hashtable (); // Private tcpclient _ client in the customer list; // Public String _ clientip in the client object; // Client IP private string _ clientnick; // client nickname private byte [] data; // message data private bool incluenick = T Rue; Public chatclient (tcpclient client) {This. _ client = client; this. _ clientip = client. Client. remoteendpoint. tostring (); // Add the current client instance? In the customer list, allclients. add (this. _ clientip, this); Data = new byte [this. _ client. receivebuffersize]; // obtain the message client from the server. getstream (). beginread (data, 0, system. convert. toint32 (this. _ client. receivebuffersize), receivemessage, null);} // obtain the public void receivemessage (iasyncresult AR) {int bytesread; try {lock (this. _ client. getstream () {bytesread = This. _ client. getstream (). endread (AR);} If (bytesread <1) {allclients. remove (this. _ clientip); broadcast (this. _ clientnick + "leaving the chat room"); return;} else {string messagereceived = system. text. encoding. ASCII. getstring (data, 0, bytesread); If (enick) {This. _ clientnick = messagereceived; broadcast (this. _ clientnick + "join chat room"); enick = false;} else {broadcast (this. _ clientnick + ":" + messagereceived) ;}} lock (this. _ client. getstream () {This. _ client. getstream (). beginread (data, 0, system. convert. toint32 (this. _ client. receivebuffersize), receivemessage, null) ;}} catch (exception ex) {allclients. remove (this. _ clientip); broadcast (this. _ clientnick + "Leave chatting room") ;}// send the public void sendmessage (string message) {try {system. net. sockets. networkstream ns; lock (this. _ client. getstream () {NS = This. _ client. getstream () ;}// encode the information byte [] bytestosend = system. text. encoding. ASCII. getbytes (Message); NS. write (bytestosend, 0, bytestosend. length); NS. flush () ;}catch (exception ex) {}// broadcast the public void broadcast (string message) {console to the client. writeline (Message); foreach (dictionaryentry C in allclients) {(chatclient) (C. value )). sendmessage (Message + environment. newline );}}}}

This is easier than just others. I copied other people's Code directly. It is better to understand than others. It is suitable for beginners ~~~ (If any copyright infringement occurs, please contact me by private letter)


The following is the code on the unity side ~

The Code is as follows:

Using unityengine; using system. collections; using system. collections. generic; using system. componentmodel; using system. text; using system. net. sockets; public class scoketclient: monobehaviour {const int Port = 20000; // port number and server port corresponding private tcpclient client; byte [] data; Public String username = ""; // username Public String message = ""; // chat content Public String sendmsg = ""; // input box void ongui () {username = GUI. textfield (New rect (10, 10,100, 20), username); message = GUI. textarea (New rect (10, 40,300,200), message); sendmsg = GUI. textfield (New rect (10,250,210, 20), sendmsg); If (GUI. button (New rect (120, 10, 80, 20), "connect to server") {This. client = new tcpclient (); this. client. connect ("127.0.0.1", Port); Data = new byte [this. client. receivebuffersize]; sendsocket (username); this. client. getstream (). beginread (data, 0, system. convert. toint32 (this. client. receivebuffersize), receivemessage, null) ;}; if (GUI. button (New rect (230,250, 80, 20), "send") {sendsocket (sendmsg); sendmsg = "" ;};} public void sendsocket (string message) {try {networkstream NS = This. client. getstream (); byte [] DATA = system. text. encoding. ASCII. getbytes (Message); NS. write (data, 0, Data. length); NS. flush ();} catch (exception ex) {}} public void receivemessage (iasyncresult AR) {try {int bytesread; bytesread = This. client. getstream (). endread (AR); If (bytesread <1) {return;} else {message + = system. text. encoding. ASCII. getstring (data, 0, bytesread);} This. client. getstream (). beginread (data, 0, system. convert. toint32 (this. client. receivebuffersize), receivemessage, null);} catch (exception ex ){}}}

In this way, you can ~ Enable the server first, and then connect with the client.

The encoding is ASCII. Suppose you want to use Chinese words into UTF-8, or gb2312.




[Unity3d self-learning Record] socket chat room on unity3d Network

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.