Unity client code:
using System; using System.Collections; using System.Net.Sockets; using System.Text; using UnityEngine; using UnityEngine.UI; public class OnlineChess : MonoBehaviour { public GameObject DengLuJieMian; public InputField InputText; public Button Zhece; public Text selfName; public Text otherName; public Text typeBy; public ToggleGroup toggleGroup; private Socket socket; private byte[] buffer = new byte[1024]; private string SetText; //--------Chess logic--------- public Transform Btns; public Transform Win; public GameObject Zi; public Sprite SpriteBlick; public Sprite SpriteWhite; public Button RePlay; public AudioSource audioSource; bool isDown = false;//Other players suddenly string jsonData = ""; bool isWin = false; //Winning or losing bool isResult = false;//Start again string playerType = "";//The player is white or black //Traverse the checkerboard squares int[] sites = new int[225];//1 is a black stone, -1 is a white stone //Traverse the current chess piece int[] number = new int[225];//The number on the chess piece int childCount = 0;//Playing chess starts from number 0, and the first piece is numbered 1 int winID = 0;//0 means no victory or defeat, 1 means black wins, -1 means white wins //Load chessboard pieces public string len = "";//Join the status of 225 chess pieces on the chessboard [HideInInspector] public Toggle[] toggles;//Choose whether to hold black or white, black moves first void Start() { toggles = toggleGroup.GetComponentsInChildren<Toggle>(); for (int i = 0; i < toggles.Length; i + + ) { Toggle toggle = toggles[i]; toggle.onValueChanged.AddListener((bool value) => OnToggleClick(toggle, value)); } Zhece.onClick.AddListener(() => { if (playerType == "" & amp; & amp; playerType == string.Empty) return; if (InputText.text.Length < 0) return; ConnectGo(); ZhuCe(); }); for (int i = 0; i < Btns.childCount; i + + ) { int k = i; Button btn = Btns.GetChild(k).GetComponent<Button>(); btn.onClick.AddListener(() => { if (btn.transform.childCount > 0) return;//Repeated moves are prohibited if (winID != 0) return;//End after victory DownChess(k.ToString()); }); } RePlay.onClick.AddListener(() => { ResultGame(); sendMass("restart"); }); } public void OnToggleClick(Toggle toggle, bool isSwitch) { Debug.Log("toogle group name:" + toggle.name + isSwitch); if (toggle.name== "Toggle1") { typeBy.text="Holding Black"; playerType = "black"; } if (toggle.name == "Toggle2") { typeBy.text = "Holding White"; playerType = "white"; } if (toggle.name == "Toggle1" & amp; & amp; !isSwitch) { playerType = string.Empty; } if (toggle.name == "Toggle2" & amp; & amp; !isSwitch) { playerType = string.Empty; } } void ConnectGo() { //AddressFamily addressing type SocketType socket type ProtocolType protocol type socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //connect to the server socket.Connect("192.168.10.220", 7777); Debug.Log("Connection successful!"); //Start receiving information readServer(); } //BB void readServer() { socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveCallback, null); } void ReceiveCallback(IAsyncResult iar) { int len = socket.EndReceive(iar); if (len == 0) return; string str = Encoding.UTF8.GetString(buffer, 0, len); SetText = str; Debug.Log(SetText); //Loop to receive data readServer(); //Analyze this string--Mass:Fafawo:5:1_1,0_0,0_3... if (SetText.Split(':').Length == 4) { if (SetText.Split(':')[0]=="Mass") { //Get the opposite move number, because the message is sent to everyone except yourself to let them update their own chessboard childCount = int.Parse(SetText.Split(':')[2]); jsonData = SetText.Split(':')[3]; if (!isDown) { isDown = true; } } } //If Heizi wins //Analyze this string--Mass:fafawa:black if (SetText.Split(':').Length == 3) { if (SetText.Split(':')[0] == "Mass") { string msg = SetText.Split(':')[2]; if (msg.Trim() == "black") { winID = 1; isWin = true; } else if (msg.Trim() == "white") { winID = -1; isWin = true; } else if (msg.Trim() == "restart") { isResult = true; } } } } //send Message public void sendServer(string msg) { //Convert the string to a UTF-8 encoded byte array var outputBuffer = Encoding.UTF8.GetBytes(msg); socket.BeginSend(outputBuffer, 0, outputBuffer.Length, SocketFlags.None, null, null); } //Bind the "Enter" button (registered user name) public void ZhuCe() { if (InputText.text != "") { selfName.text = InputText.text; string msg = "userName:" + InputText.text + "\r\ "; sendServer(msg); DengLuJieMian.SetActive(false); } } //Bind the "Send" button (group message) public void sendMass(string str) { if (str != "") { string msg = "Mass:" + selfName.text + ":" + str + "\r\ "; sendServer(msg); } } //Listen and update the status of other clients private void Update() { //all of a sudden if(isDown) { DrawChess(jsonData); } //restart if(isResult) { ResultGame(); } //Winning or losing if(isWin) { if (winID == 1) { Win.GetChild(0).gameObject.SetActive(true); } if (winID == -1) { Win.GetChild(1).gameObject.SetActive(true); } isWin = false; } } void ResultGame() { for (int i = 0; i < Btns.childCount; i + + ) { if (Btns.GetChild(i).childCount > 0) { Destroy(Btns.GetChild(i).GetChild(0).gameObject); } } Win.GetChild(0).gameObject.SetActive(false); Win.GetChild(1).gameObject.SetActive(false); for (int i = 0; i < 225; i + + ) { sites[i] = 0; } for (int i = 0; i < 225; i + + ) { number[i] = 0; } childCount = 0; winID = 0; isResult = false; } public void DownChess(string str) { if (winID == 0) { int foo = int.Parse(str); len = ""; //If the number of chess pieces is an even number, you can only play black pieces. if (childCount % 2 == 0 & amp; & amp; playerType == "black") { childCount + + ; sites[foo] = 1;//Mark the sunspots whose status 1 is down } else if (childCount % 2 == 1 & amp; & amp; playerType == "white") { childCount + + ; sites[foo] = -1;//Mark the white piece with status -1 as down } Debug.Log("Current number of chess pieces: " + childCount); //chess piece number number[foo] = childCount; for (int i = 0; i < 225; i + + ) { if (i < 224) { len + = sites[i] + "_" + number[i] + ","; } else { len + = sites[i] + "_" + number[i]; } } //len + = means concatenating string strings //Example result analysis: //1_3,0_0,-1_9,0_0... means that a black piece was placed on the first position of the chessboard in the third step, and the piece number is 3. //The third position, the ninth step, and the white stone number is 9 //Update your own chessboard status first //Observe the server code if(client != socket) //If the server does not ignore self-generation, it can log out this line first and wait to update the chessboard status with all clients. DrawChess(len); //Tell others sendMass(childCount + ":" + len); } } void DrawChess(string str) { for (int i = 0; i < 225; i + + ) { int num = int.Parse(str.Split(',')[i].Split('_')[0]);//drop point int num2 = int.Parse(str.Split(',')[i].Split('_')[1]);//position number //if(num != 0) if (num == 1 || num == -1) { if (Btns.GetChild(i).childCount == 0) { GameObject go = Instantiate(Zi); go.transform.SetParent(Btns.GetChild(i)); go.transform.localPosition = Vector3.zero; audioSource.Play();//Sound effects of chess moves go.transform.GetComponent<Image>().sprite = num == 1 ? SpriteBlick : SpriteWhite; go.transform.GetChild(0).GetComponent<Text>().text = num2.ToString(); go.SetActive(true); ResultWin(); } } } isDown = false; } void ResultWin() { for (int i = 0; i < 225; i + + ) { if (i % 15 < 11) { GetWin(i, 1, 0); if (i < 165) { GetWin(i, 15, 1); } } if (i < 165) { GetWin(i, 15, 0); if (i % 15 > 3) { GetWin(i, 15, -1); } } } } private void GetWin(int childID, int v, int xieID) { if (Btns.GetChild(childID).childCount > 0 & amp; & amp; Btns.GetChild(childID + v * 1 + 1 * xieID).childCount > 0 & amp; & amp; Btns.GetChild(childID + v * 2 + 2 * xieID).childCount > 0 & amp; & amp; Btns.GetChild(childID + v * 3 + 3 * xieID).childCount > 0 & amp; & amp; Btns.GetChild(childID + v * 4 + 4 * xieID).childCount > 0) { if (Btns.GetChild(childID).GetChild(0).GetComponent<Image>().sprite.name == Btns.GetChild(childID + v * 1 + 1 * xieID).GetChild(0).GetComponent<Image>().sprite.name & amp; & amp; Btns.GetChild(childID + v * 1 + 1 * xieID).GetChild(0).GetComponent<Image>().sprite.name == Btns.GetChild(childID + v * 2 + 2 * xieID).GetChild(0).GetComponent<Image>().sprite.name & amp; & amp; Btns.GetChild(childID + v * 2 + 2 * xieID).GetChild(0).GetComponent<Image>().sprite.name == Btns.GetChild(childID + v * 3 + 3 * xieID).GetChild(0).GetComponent<Image>().sprite.name & amp; & amp; Btns.GetChild(childID + v * 3 + 3 * xieID).GetChild(0).GetComponent<Image>().sprite.name == Btns.GetChild(childID + v * 4 + 4 * xieID).GetChild(0).GetComponent<Image>().sprite.name ) { if (Btns.GetChild(childID).GetChild(0).GetComponent<Image>().sprite.name == "black") { Win.GetChild(0).gameObject.SetActive(true); } if (Btns.GetChild(childID).GetChild(0).GetComponent<Image>().sprite.name == "white") { Win.GetChild(1).gameObject.SetActive(true); } //Tell others sendMass(Btns.GetChild(childID).GetChild(0).GetComponent<Image>().sprite.name); } } } }
The unity server code is a naked socket. Broadcast messages to all clients except itself. The server-side code is in the next article.