程序分别为服务端与客户端,服务端创建套接字使用多线程侦听多客户端请求
代码需要引用System.Net;和System.Net.Socket;这两个类
分享源码demo:https://pan.baidu.com/s/10RuE9Vk0cIoxY91uzx4Gig 提取码:4eds
运行图:
服务端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleServer
{
class Program
{
static void Main(string[] args)
{
ServerControl Server = new ServerControl();//初始化Socket
Server.Start();//启动侦听连接
//Console.WriteLine("123");
Console.Read();
}
}
}
展开查看代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace ConsoleServer
{
public class ServerControl
{
public Socket ServerSocket;
public List
/// <summary>
/// 构造函数
/// </summary>
public ServerControl()
{
//创建套接字,ipv4寻址方式,套接字类型,传输协议
ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ClientList=new List<Socket>();//实例化客户端接入集合介入
}
public void Start()
{
ServerSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"),));//绑定IP和端口
ServerSocket.Listen();//支持最多连接数
Console.WriteLine("start server succeed");
//当有客户接入时当前线程会被挂起,每次新接入客户端创建独立线处理
Thread ThreadAccept = new Thread(Accept);
ThreadAccept.IsBackground = true;//设置为后台线程
ThreadAccept.Start();//启动线程
}
private void Accept()
{
Socket Client = ServerSocket.Accept();//客户端接入当前线程挂起
IPEndPoint point=Client.RemoteEndPoint as IPEndPoint;//将远端节点转为ip和端口
Console.WriteLine("IP {0}:{1} connect succeed",point.Address,point.Port);//显示接入信息
ClientList.Add(Client);//将此连接添加到客户集合
//接收消息只处理一次,线程被挂起,创建新线程处理其新消息
Thread ThreadReceive = new Thread(Receive);
ThreadReceive.IsBackground = true;//设置为后台线程
ThreadReceive.Start(Client);//启动线程
Accept();//回掉处理新接入客户端
}
/// <summary>
/// 处理收到的消息
/// </summary>
/// <param name="obj"></param>
private void Receive(object obj)
{
Socket Client = obj as Socket;
IPEndPoint point = Client.RemoteEndPoint as IPEndPoint;//将远端节点转为ip和端口
try
{
byte\[\] ByteReceive = new byte\[\];//消息数组
int ReceiveLenght = Client.Receive(ByteReceive);//只处理一次消息,此处会被挂起
string msg = point.Address + "\[" + point.Port + "\]:" + Encoding.UTF8.GetString(ByteReceive, , ReceiveLenght);
Console.WriteLine(msg);//打印收到的消息
Broadcast(Client, msg);//广播消息
Client.Send(Encoding.UTF8.GetBytes(DateTime.Now.ToString()));//回发当前时间给消息源
Receive(Client);//回调处理新消息
}
catch
{
ClientList.Remove(Client);//当客户端断开,从客户端集合移除该客户端
Console.WriteLine("{0}\[{1}\]:断开连接", point.Address, point);//打印提示信息
}
}
/// <summary>
/// 广播消息
/// </summary>
/// <param name="cli"></param>
/// <param name="msg"></param>
public void Broadcast(Socket cli,string msg)
{
foreach (var item in ClientList )//遍历所有客户端
{
if (item != cli)
item.Send(Encoding.UTF8.GetBytes(msg));//给除数据源以外客户端发送广播消息
}
}
}
}
展开查看代码
客户端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleClient
{
class Program
{
static void Main(string[] args)
{
ClientControl Client = new ClientControl();//初始化Socket
Client.Connect("127.0.0.1",);//连接到服务器
Console.WriteLine("Please enter the content to send,Enter exit to exit!");//提示信息
string msg=Console.ReadLine();//输入
while (msg!="exit")//判断是否退出
{
Client.Send(msg);//发送消息
msg = Console.ReadLine();//输入消息
}
}
}
}
展开查看代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace ConsoleClient
{
public class ClientControl
{
private Socket ClientSocket;
public ClientControl()
{
//创建套接字,ipv4寻址方式,套接字类型,传输协议
ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
/// <summary>
/// 连接到服务器
/// </summary>
/// <param name="IP"></param>
/// <param name="Port"></param>
public void Connect(string IP, Int32 Port)
{
try
{
ClientSocket.Connect(IP, Port);//连接到指定服务器
Console.WriteLine("connect server succeed ok!");//提示信息
//收到消息是线程会被挂起,创建新线程处理收到的消息
Thread ThreadReceive = new Thread(Receive);
ThreadReceive.IsBackground = true;
ThreadReceive.Start();
}
catch(SocketException e)
{
Console.WriteLine("无法连接到{0}:{1}{2}",IP,Port,e);
}
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="msg"></param>
public void Send(string msg)
{
ClientSocket.Send(Encoding.UTF8.GetBytes(msg));
}
/// <summary>
/// 接收消息
/// </summary>
private void Receive()
{
try
{
byte\[\] ByteReceive = new byte\[\];
int ReceiveLenght = ClientSocket.Receive(ByteReceive);//此处线程会被挂起
Console.WriteLine("{0}", Encoding.UTF8.GetString(ByteReceive, , ReceiveLenght));
Receive();
}
catch
{
Console.WriteLine("服务器已断开");
}
}
}
}
展开查看代码
手机扫一扫
移动阅读更方便
你可能感兴趣的文章