客户端:
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using UnityEngine;
using UnityEngine.UI;
public class Client : MonoBehaviour
{
public InputField send_text;//用来获取用户界面输入的信息
public Text show;//显示是否连接
public Text showing_text;//显示已经发送的消息
Socket socket;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(socket == null)
{
show.text = "未连接";
}
else
{
show.text = "已连接";
}
}
public void Connected()
{
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//IPAddress iPAddress = Dns.GetHostEntry(127.0.0.1)
socket.Connect("127.0.0.1", 8888);//连接的服务器地址和端口
}
catch(SocketException ex)
{
socket = null;
Debug.Log("连接失败" + ex.ToString());
}
}
public void Send()
{
//byte[] bytes = new byte[1024];//创建容器用来储存服务器传来的消息
string send_mas = send_text.text;
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(send_mas);
socket.Send(bytes);
int count = send_text.text.Length;
string showing = System.Text.Encoding.UTF8.GetString(bytes);
showing_text.text = showing;
}
public void Break()
{
socket.Close();//关闭客户端
}
}
在unity中创建对应的组件,分别为不同的按钮选择监听事件
服务器:
using System;
using System.Net;
using System.Net.Sockets;
namespace Severmyself
{
class Program
{
static Socket socket;
static void Main(string[] args)
{
try
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//定义运转环境,传输方式,传输协议
IPAddress iP = IPAddress.Parse("127.0.0.1");
IPEndPoint endPoint = new IPEndPoint(iP, 8888);//定义网络终端
socket.Bind(endPoint);
socket.Listen(100);//定义最大连接数并且将程序由主动连接变为被动连接
Console.WriteLine("服务器启动成功!");
Socket socket1 = socket.Accept();
byte[] bytes = new byte[1024];//定义储存客户端发来的数据
int count = socket1.Receive(bytes);
count = socket1.Receive(bytes);
string Receive_mas = System.Text.Encoding.UTF8.GetString(bytes, 0, count);
Console.WriteLine("客户端:" + Receive_mas);
Console.ReadLine();
socket1.Close();
}
catch (SocketException ex)
{
Console.WriteLine("Connect was failed" + ex.ToString());
}
}
}
}
由于实现的是单个客户端与服务器的连接,所以这里面的监听只调用了一次,也就是说,仅能处理一个客户端的请求。