1122人加入学习
(14人评价)
网络零基础入门 - 欢乐斗地主第一季

零基础Socket网络编程入门(基于Unity2021)

价格 ¥ 330.00

Server:

byte[] readBuff;

string receiveStr;

Main():

{

serverSocket.Bind(IPEndPoint("127.0.0.1",8888));

serverSocket.Listen(0);

==服务器启动成功==

serverSocket.BeginAccept(AcceptCallback, serverSocket);

Console.ReadLine();

}

AcceptCallback(IAsyncResult ar):

{

serverSocket = ar.AsyncState as Socket;

clientSocket=serverSocket.EndAccept(ar);

==有一个客户端Accept==

clientSocket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallback, clientSocket);

serverSocket.BeginAccept(AcceptCallback, serverSocket);

}

ReceiveCallback(IAsyncResult ar):

{

Socket clientSocket = ar.AsyncState as Socket;

int count = clientSocket.EndReceive(ar);
if (count == 0)
{
    clientSocket.Close();
    Console.WriteLine("客户端断开连接");
    return;
}

receiveStr=Encoding.UTF8.GetString(readBuff, 0, count);

=={receiveStr}==

clientSocket.BeginSend(Encoding.UTF8.GetBytes(receiveStr), 0, receiveStr.Length, 0, SendCallback, clientSocket);

clientSocket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallback, clientSocket);

}

SendCallback(IAsyncResult ar):

{

Socket clientSocket = ar.AsyncState as Socket;

clientSocket.EndSend(ar);

}

 

Client:

Socket socket;

byte[] readBuff;

string receiveStr;

Connect():

{

socket.BeginConnect("127.0.0.1",8888, ConnectCallback,socket);

}

ConnectCallback(IAsyncResult ar):

{

Socket socket = (Socket)ar.AsyncState;
socket.EndConnect(ar);

==连接成功==

socket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallback, socket);

}

ReceiveCallback(IAsyncResult ar):

{

Socket socket = ar.AsyncState as Socket;

int count = socket.EndReceive(ar);

receiveStr = Encoding.UTF8.GetString(readBuff, 0, count);

socket.BeginReceive(readBuff, 0, 1024, 0, ReceiveCallback, socket);

}

Send():

{

string sendStr = InputField.text;
byte[] sendBytes =Encoding.UTF8.GetBytes(sendStr);

socket.BeginSend(sendBytes, 0, sendBytes.Length, 0, SendCallback, socket);

}

SendCallback(IAsyncResult ar):

{

Socket socket = ar.AsyncState as Socket;
int count = socket.EndSend(ar);

==发送成功{count}==

}

[展开全文]

TCP:确保数据准确无误的传递

UDP:确保数据实时传递,会产生数据丢失

[展开全文]

授课教师

Unity开发者

课程特色

下载资料(1)
视频(28)