我之前寫博客是為了寫而寫,不管質(zhì)量都亂寫,有時(shí)間得去清理一下。 說來感覺自己好悲哀啊,出去實(shí)習(xí)沒做過網(wǎng)游,也幾乎沒用Socket,所以現(xiàn)在在學(xué)校沒事做必須多了解一些網(wǎng)絡(luò)通信這類的東西,從頭開始學(xué)吧,呵呵。下面這個例子第一個很簡單,大家別笑我哈,我很菜的。這個例子是用Socket的TCP協(xié)議做的,當(dāng)然也可以用UDP和TCPListener來做。也沒用到多線程啊,呵呵,其實(shí)就是為了看看里面的一些函數(shù)而已。 Server.cs: - using UnityEngine;
- using System.Collections;
- using System.Net;
- using System.IO;
- using System.Net.Sockets;
- using System.Text;
-
- public class Server : MonoBehaviour {
-
- void Start () {
- OpenServer();
- }
-
- void OpenServer()
- {
- IPAddress ipAdr = IPAddress.Parse("10.56.03.32");
- IPEndPoint ipEp = new IPEndPoint(ipAdr , 1234);
- Socket serverScoket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
- serverScoket.Bind (ipEp);
- serverScoket.Listen(20);
- while(true)
- {
- Socket client = serverScoket.Accept();
- byte[] request = new byte[512];
- int bytesRead = client.Receive(request);
- string input = Encoding.UTF8.GetString(request,0,bytesRead);
- print("server request:"+input);
- string output = "連接服務(wù)器成功~~~~";
- byte[] concent = Encoding.UTF8.GetBytes(output);
- client.Send(concent);
- client.Shutdown(SocketShutdown.Both);
- client.Close();
- }
- }
- }
Client.cs: - using UnityEngine;
- using System.Collections;
- using System.Text;
- using System.Net;
- using System.Net.Sockets;
- using System.IO;
-
-
- public class Client : MonoBehaviour {
-
- void Start () {
- ConncetServer();
- }
-
- void ConncetServer()
- {
- IPAddress ipAdr = IPAddress.Parse("10.56.03.32");
- IPEndPoint ipEp = new IPEndPoint(ipAdr , 1234);
- Socket clientScoket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
- clientScoket.Connect(ipEp);
- string output = "客戶端請求連接~~~";
- byte[] concent = Encoding.UTF8.GetBytes(output);
- clientScoket.Send(concent);
- byte[] response = new byte[1024];
- int bytesRead = clientScoket.Receive(response);
- string input = Encoding.UTF8.GetString(response,0,bytesRead);
- print("Client request:"+input);
- clientScoket.Shutdown(SocketShutdown.Both);
- clientScoket.Close();
- }
- }
服務(wù)端:
1).用Socket()獲得一個Socket描述 2).用Bind()j將Socket綁定到一個網(wǎng)絡(luò)地址(一般都是本機(jī)的IP地址) 3).用Listen()開始在某個端口監(jiān)聽 4).Accept()等待客戶連接,如果客戶端調(diào)用Connect()函數(shù)連接服務(wù)器時(shí)Accept()會獲得該客戶端(Socket)。 5).Receive()接收數(shù)據(jù) 6).Send()發(fā)送數(shù)據(jù) 客戶端: 1).用Socket()獲取一個Socket描述 2).Connect()連接到遠(yuǎn)程主機(jī) 3).Send()發(fā)送數(shù)據(jù) 4).Receive()接收數(shù)據(jù)
|