客户端代码:
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();//关闭客户端
return;
}
}
当客户端与服务器连接之后异常关闭(直接令客户端程序退出)时,服务器应当释放绑定的客户端所占有的资源,上一篇博客中仅仅是客户端与服务器的简单应用,客户端不能多次给服务器发送消息,并且,当客户端关闭(正常非正常)的时候,服务器没有释放相应的资源。
改进代码
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);
while (count != 0)//如果为0,则说明客户端已经断开连接
{
string yonghu = Console.ReadLine();
count = socket1.Receive(bytes);
string Receive_mas = System.Text.Encoding.UTF8.GetString(bytes, 0, count);
Console.WriteLine("客户端:" + Receive_mas);
}
string back = "未连接";
byte[] byte_send = System.Text.Encoding.UTF8.GetBytes(back);
socket.Send(byte_send);
socket1.Close();
}
catch (SocketException ex)
{
Console.WriteLine("Connect was failed" + ex.ToString());
}
}
}
}
以上只是自己的解题思路,如果有错误欢迎纠正