网络通讯C#(TCP)简单实现通讯
2020-12-27 12:28
标签:utf8 终结点 enc kms 地址 ons end 缓存 gets using System; using System.Net; //构造函数 //检测客户端是否连接 //开启后台线程,进行客户端的会话 thClientMsg.IsBackground = true; //定义成后台线程 using System; using System.Net; public Client() try } Console.WriteLine("我:"+strMsg); } static void Main(string[] args) clientObj.SendMsg(); } 网络通讯C#(TCP)简单实现通讯 标签:utf8 终结点 enc kms 地址 ons end 缓存 gets 原文地址:https://www.cnblogs.com/-831/p/13344871.html
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;//套接字
using System.Threading;//线程
namespace ConsoleApp1
{
///
/// 服务器端
///
///
class Sever
{
private Socket _SockSever; //服务器监听套接字
private bool _IsListenContect=true; // 是否监听服务器(方便退出)
public Sever()
{
//定义网络终结点(封装IP与端口)
IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.20.102"),8585);//地址与端口号 ip 127.0.0.1 代表本机
//实例化 定义SockSever套接字 TCP是面向流来传输的所以用Stream
_SockSever = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//服务器端绑定地址
_SockSever.Bind(endPoint);
//开始监听
_SockSever.Listen(10);//10 表示“监听队列”最大长度 等于最多链接服务器的数量 起限制的作用
Console.WriteLine("服务器端已启动");
try
{
while (_IsListenContect)
{
//Accept 方法 : 接受客户端的连接方法
//这个方法会阻断当前的线程
Socket sockMsgSever = _SockSever.Accept();
Console.WriteLine("有一个客户端连接");
Thread thClientMsg = new Thread(ClientMsg);
thClientMsg.Name = "thClientMsg";
thClientMsg.Start(sockMsgSever);
}
}
catch (Exception)
{
}
}
public void ClientMsg(object sockMsg)
{
Socket socketMsg= sockMsg as Socket; //通讯Socket
while (true)
{
//准备一个“数据缓存”
byte[] msgArray = new byte[1024 * 1024];//1M空间
//接收客户端发来的数据,返回数据真实的长度。
int trueClientMsgLength= socketMsg.Receive(msgArray);
//byte数组转String
string strMsg= Encoding.UTF8.GetString(msgArray, 0, trueClientMsgLength);
//显示消息
Console.WriteLine(strMsg);
}
}
static void Main(string[] args)
{
Sever severObj = new Sever();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
///
/// 客户端
///
namespace ConsoleApp2
{
class Client
{
private Socket _SockClient; //客户端的通讯套接字
private IPEndPoint secerEndPoint; //连接到服务器IP与端口
{
//封装服务器的IP与端口
secerEndPoint = new IPEndPoint(IPAddress.Parse("192.168.20.102"), 8585);
//建立客户端Sockt
_SockClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
{
_SockClient.Connect(secerEndPoint);
}
catch (Exception)
{
}
Console.WriteLine("连接服务器成功");
public void SendMsg()
{
while (true)
{
//输入信息
string strMsg= Console.ReadLine();
//退出
if (strMsg=="退出")
{
break;
}
//字节转换
byte[] byteArray = Encoding.UTF8.GetBytes(strMsg);
//发送数据
_SockClient.Send(byteArray);
//禁用链接
_SockClient.Shutdown(SocketShutdown.Both);
//关闭连接
_SockClient.Close();
}
{
Client clientObj = new Client();
}
}