using
System.Collections;
using
System.Collections.Generic;
using
System.Net.Sockets;
using
UnityEngine;
using
UnityEngine.UI;
using
System.Text;
using
System;
using
System.Linq;
public
class
net
:
MonoBehaviour
{
int
buffCount = 0;
byte
[] lenBytes =
new
byte
[
sizeof
(
UInt32
)];
//与Int都是4字节 带U的没有负数
Int32
msgLength = 0;
public
InputField
hostInput;
public
InputField
portInput;
//文本框
public
Text
recvText;
public
string
recvStr;
public
Text
clientText;
//聊天输入框
public
InputField
textInput;
//Socket和接收缓冲区
Socket
socket;
public
Button
sengBtn;
//接收缓冲区
const
int
BUFFER_SIZE = 1024;
public
byte
[] readBuffer =
new
byte
[BUFFER_SIZE];
public
Button
chatBtn;
public
void
Connetion()
{
recvText.text =
""
;
socket =
new
Socket
(
AddressFamily
.InterNetwork,
SocketType
.Stream,
ProtocolType
.Tcp);
string
host = hostInput.text;
int
port =
int
.Parse(portInput.text);
socket.Connect(host, port);
clientText.text =
"客户端地址"
+ socket.LocalEndPoint.ToString();
socket.BeginReceive(readBuffer,0,BUFFER_SIZE,
SocketFlags
.None,ReceiveCb,
null
);
}
private
void
ReceiveCb(
IAsyncResult
ar)
{
try
{
//count是接收数据的大小
int
count = socket.EndReceive(ar);
//数据处理
buffCount += count;
ProcessData();
//继续接收
socket.BeginReceive(readBuffer, 0, BUFFER_SIZE,
SocketFlags
.None, ReceiveCb,
null
);
}
catch
(
Exception
)
{
recvText.text +=
"连接已断开"
;
socket.Close();
}
}
private
void
ProcessData()
{
//小于长度字节 4
if
(buffCount <
sizeof
(
Int32
))
return
;
//消息长度
Array
.Copy(readBuffer, lenBytes,
sizeof
(
Int32
));
msgLength =
BitConverter
.ToInt32(lenBytes, 0);
if
(buffCount < msgLength +
sizeof
(
Int32
))
return
;
//处理消息
string
protocol =
Encoding
.UTF8.GetString(readBuffer,
sizeof
(
Int32
), msgLength);
HandleMsg(protocol);
//清除已处理的消息
int
count = buffCount - msgLength -
sizeof
(
Int32
);
Array
.Copy(readBuffer, msgLength, readBuffer, 0, count);
buffCount = count;
if
(buffCount > 0)
{
ProcessData();
}
}
private
void
HandleMsg(
string
protoBase)
{
string
proto =protoBase;
Debug
.Log(
"接收 "
+ proto);
}
//发送数据
public
void
Send()
{
string
str= textInput.text;
byte
[] bytes =
Encoding
.UTF8.GetBytes(str);
byte
[] length =
BitConverter
.GetBytes(bytes.Length);
byte
[] sendbuff = length.Concat(bytes).ToArray();
socket.Send(sendbuff);
}
// Use this for initialization
void
Start
() {
sengBtn.onClick.AddListener(sengBtnCallBack);
chatBtn.onClick.AddListener(chatBtnCallBack);
}
private
void
chatBtnCallBack()
{
Send();
}
private
void
sengBtnCallBack()
{
hostInput.text=
"127.0.0.1"
;
portInput.text =
"9568"
;
Connetion();
}
//因为只有主线程能够改UI组件的属性、
//因此在Upadate里更换脚步
void
Update
() {
recvText.text = recvStr;
}
}