我之前写博客是为了写而写,不管质量都乱写,有时间得去清理一下。 说来感觉自己好悲哀啊,出去实习没做过网游,也几乎没用Socket,所以现在在学校没事做必须多了解一些网络通信这类的东西,从头开始学吧,呵呵。下面这个例子第一个很简单,大家别笑我哈,我很菜的。这个例子是用Socket的TCP协议做的,当然也可以用UDP和TCPListener来做。也没用到多线程啊,呵呵,其实就是为了看看里面的一些函数而已。 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 = "连接服务器成功~~~~";
- 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();
- }
- }
服务端:
1).用Socket()获得一个Socket描述 2).用Bind()j将Socket绑定到一个网络地址(一般都是本机的IP地址) 3).用Listen()开始在某个端口监听 4).Accept()等待客户连接,如果客户端调用Connect()函数连接服务器时Accept()会获得该客户端(Socket)。 5).Receive()接收数据 6).Send()发送数据 客户端: 1).用Socket()获取一个Socket描述 2).Connect()连接到远程主机 3).Send()发送数据 4).Receive()接收数据
|