using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
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.IsBackground = true; //定义成后台线程
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;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
///
/// 客户端
///
namespace ConsoleApp2
{
class Client
{
private Socket _SockClient; //客户端的通讯套接字
private IPEndPoint secerEndPoint; //连接到服务器IP与端口
public Client()
{
//封装服务器的IP与端口
secerEndPoint = new IPEndPoint(IPAddress.Parse("192.168.20.102"), 8585);
//建立客户端Sockt
_SockClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
_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);
Console.WriteLine("我:"+strMsg);
}
//禁用链接
_SockClient.Shutdown(SocketShutdown.Both);
//关闭连接
_SockClient.Close();
}
static void Main(string[] args)
{
Client clientObj = new Client();
clientObj.SendMsg();
}
}
}
网络通讯C#(TCP)简单实现通讯