//服务器端
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Net;
using
System.Net.Sockets;
namespace
net
{
class
Program
{
static
void
Main(
string
[] args)
{
Socket
listend =
new
Socket
(
AddressFamily
.InterNetwork,
SocketType
.Stream,
ProtocolType
.Tcp);
IPAddress
ipadr =
IPAddress
.Parse(
"127.0.0.1"
);
IPEndPoint
ipEp =
new
IPEndPoint
(ipadr,1234);
listend.Bind(ipEp);
listend.Listen(0);
Console
.WriteLine(
"服务器启动成功"
);
while
(
true
)
{
//acppet
Socket
connfd = listend.Accept();
Console
.WriteLine(
"服务器Accpt"
);
byte
[] readBulf =
new
byte
[1024];
int
count = connfd.Receive(readBulf);
string
str = System.Text.
Encoding
.UTF8.GetString(readBulf,0,count);
Console
.WriteLine(
"服务器接收"
+str);
//协议
byte
[] bytes = System.Text.
Encoding
.UTF8.GetBytes(
"scer"
+str);
connfd.Send(bytes);
}
}
}
}
//——-------------- --------- --------- -- -- --------
using
UnityEngine;
using
System.Collections;
using
System.Net;
using
System.Net.Sockets;
///
<summary>
///
客户端
///
</summary>
public
class
Net
:
MonoBehaviour
{
Socket
socket;
const
int
BUFFER_SIZE = 1024;
byte
[] readBuf =
new
byte
[BUFFER_SIZE];
void
Start() {
Connection();
}
public
void
Connection() {
socket =
new
Socket
(
AddressFamily
.InterNetwork,
SocketType
.Stream,
ProtocolType
.Tcp);
string
host =
"127.0.0.1"
;
int
port = 1234;
socket.Connect(host,port);
Debug
.Log(
"客户端地址"
+socket.LocalEndPoint.ToString());
string
str =
"nihao"
;
byte
[] bytes = System.Text.
Encoding
.UTF8.GetBytes(str);
socket.Send(bytes);
int
count = socket.Receive(readBuf);
//使用的协议必须一样 如果bytes转化使用UTF8 ,那么字符串也同样使用UTF8 否则发送中文会乱码
str = System.Text.
Encoding
.UTF8.GetString(readBuf,0,count);
Debug
.Log(
"发送成功"
+str);
socket.Close();
}
}