主要实现服务器与客户端之间简单的数据传输(单次)
服务器代码
using System;
using System.Net;
using System.Net.Sockets;
namespace SeverSocket
{
class Program
{
static void Main(string[] args)
{
//创建服务器
Socket severSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//ip地址和端口号绑定
EndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.213.54"),10001);
//绑定服务器
severSocket.Bind(endPoint);
//发起监听
severSocket.Listen(1000);
Console.WriteLine("服务器已经启动成功!!!!");
while (true)
{
Console.WriteLine("等待客户端链接");
Socket cilentSocket = severSocket.Accept();//这里会阻塞,等待链接
Console.WriteLine("有新的用户链接!!!!");
Console.WriteLine("请输入要发给客户端的内容:");
string readLine = Console.ReadLine();
byte[] sendMsg = System.Text.Encoding.UTF8.GetBytes(readLine);
int sendLength= cilentSocket.Send(sendMsg,SocketFlags.None);
Console.WriteLine("发送消息成功,发送的消息长度是:"+sendLength);
//接收
Console.WriteLine("开始接收消息");
byte[] buffer = new byte[512];
int receivelength = cilentSocket.Receive(buffer);
//输出一下接收到的内容
string receiveMsg = System.Text.Encoding.UTF8.GetString(buffer);
Console.WriteLine("接收到的消息是:"+receiveMsg);
}
}
}
}
客户端代码
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System;
/// <summary>
/// 客户端的控制脚本
/// </summary>
public class ClientSocketController : MonoBehaviour {
/// <summary>
/// 链接对象
/// </summary>
public Socket clientSocket;
/// <summary>
/// ip地址
/// </summary>
public string ipAddress = "192.168.213.54";
/// <summary>
/// 端口号,这个是服务器开设的端口号
/// </summary>
public int portNumber = 10001;
/// <summary>
/// 链接间隔时间
/// </summary>
public float connectInterval = 1;
/// <summary>
/// 当前链接时间
/// </summary>
public float connectTime = 0;
/// <summary>
/// 链接次数
/// </summary>
public int connectCount = 0;
/// <summary>
/// 是否在连接中
/// </summary>
public bool isConnecting=false;
void Start () {
//调用开始连接
ConnectedToServer();
}
/// <summary>
/// 链接到服务器
/// </summary>
public void ConnectedToServer()
{
//链接次数增加
connectCount++;
isConnecting = true;
Debug.Log("这是第"+connectCount+"次链接");
//如果客户端不为空
if (clientSocket!=null)
{
try
{
//断开连接,释放资源
clientSocket.Disconnect(false);
clientSocket.Close();
}
catch (System.Exception e)
{
Debug.Log(e.ToString());
}
}
//创建新的链接(固定格式)
clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//设置端口号和ip地址
EndPoint endPoint = new IPEndPoint(IPAddress.Parse(ipAddress),portNumber);
//发起链接
clientSocket.BeginConnect(endPoint,OnConnectCallBack,"");
}
/// <summary>
/// 开始链接的回调
/// </summary>
/// <param name="ar"></param>
public void OnConnectCallBack(IAsyncResult ar)
{
Debug.Log("链接完成!!!!");
if (clientSocket.Connected)
{
//链接成功
Debug.Log("链接成功");
connectCount = 0;
//开启收消息
ReceiveFormServer();
}
else
{
//链接失败
Debug.Log("链接失败");
//计时重置
connectTime = 0;
}
isConnecting = false;
//结束链接
clientSocket.EndConnect(ar);
}
/// <summary>
/// 向服务器发送字符串信息
/// </summary>
/// <param name="msg"></param>
public void SendMessageToServer(string msg)
{
//将字符串转成byte数组
byte[] msgBytes = System.Text.Encoding.UTF8.GetBytes(msg);
clientSocket.BeginSend(msgBytes,0,msgBytes.Length,SocketFlags.None,SendMassageCallBack,1);
}
/// <summary>
/// 发送信息的回调
/// </summary>
/// <param name="ar"></param>
public void SendMassageCallBack(IAsyncResult ar)
{
//关闭消息发送
int length=clientSocket.EndSend(ar);
Debug.Log("信息发送成功,发送的信息长度是:"+length);
}
/// <summary>
/// 从服务器接收消息
/// </summary>
public void ReceiveFormServer()
{
//定义缓冲池
byte[] buffer = new byte[512];
clientSocket.BeginReceive(buffer,0,buffer.Length,SocketFlags.None,ReceiveFormServerCallBack,buffer);
}
/// <summary>
/// 信息接收方法的回调
/// </summary>
/// <param name="ar"></param>
public void ReceiveFormServerCallBack(IAsyncResult ar)
{
//结束接收
int length=clientSocket.EndReceive(ar);
byte[] buffer = (byte[])ar.AsyncState;
//将接收的东西转为字符串
string msg = System.Text.Encoding.UTF8.GetString(buffer,0,length);
Debug.Log("接收到的消息是:"+msg);
//开启下一次接收消息
ReceiveFormServer();
}
void Update () {
if (Input.GetMouseButton(0))
{
SendMessageToServer("吾于杀戮之中绽放,亦如黎明中的花朵!");
}
if (clientSocket!=null && clientSocket.Connected==false)
{
//链接没有成功
//计时
connectTime += Time.deltaTime;
if (connectTime > connectInterval && isConnecting == false)//如果时间大于链接重置时间间隔且没有链接
{
if (connectCount >= 7)
{
Debug.Log("已经尝试了7次,请检查网络连接");
clientSocket = null;
}
else
{
//重连一次
ConnectedToServer();
}
}
}
}
private void OnDestroy()
{
Debug.Log("物体被销毁");
//关闭客户端
clientSocket.Close();
}
}
小结:服务器与客户端传递的数据格式要保持一致