1.socket介绍
所谓套接字(socket),就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象。一个套接字就是网络上进程通信的一端,提供了应用层进程利用网络协议交换数据的机制。从所处的地位来讲,套接字上联应用进程,下联网络协议栈,是应用程序通过网络协议进行通信的接口,是应用程序与网络协议栈进行交互的接口
2.socket一般应用模式(服务器端和客户端)
3.socket的通讯过程
4.socket通信基本流程图:
5.项目界面设计:
6.实现核心代码
using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.threading.tasks;
using system.windows.forms;
using system.net;
using system.net.sockets;
namespace tcpprogect
{
public partial class frmserver : form
{
public frmserver()
{
initializecomponent();
}
//第一步:调用socket()函数创建一个用于通信的套接字
private socket listensocket;
//字典集合:存储ip和socket的集合
private dictionary<string, socket> onlinelist = new dictionary<string, socket>();
//当前时间
private string currenttime
{
get { return datetime.now.tostring("hh:mm:ss") + environment.newline; }
}
//编码格式
encoding econding = encoding.default;
private void btn_startservice_click(object sender, eventargs e)
{
//第一步:调用socket()函数创建一个用于通信的套接字
listensocket = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
//第二步:给已经创建的套接字绑定一个端口号,这一般通过设置网络套接口地址和调用bind()函数来实现
ipendpoint endpoint = new ipendpoint(ipaddress.parse(this.txt_ip.text.trim()), int.parse(this.txt_port.text.trim()));
try
{
listensocket.bind(endpoint);
}
catch (exception ex)
{
messagebox.show("服务器开启失败:" + ex.message, "开启服务器");
return;
}
//第三步:调用listen()函数使套接字成为一个监听套接字
listensocket.listen(10);
showmessage("服务器开启成功");
//开启一个线程监听
task.run(new action(() =>
{
listenconnection();
}
));
this.btn_startservice.enabled = false;
}
private void listenconnection()
{
while (true)
{
socket clientsocket = listensocket.accept();
string ip = clientsocket.remoteendpoint.tostring();
//更新在线列表
addonline(ip, true);
//更新在线列表集合
onlinelist.add(ip, clientsocket);
showmessage(ip + "上线了");
task.run(() => receivemsg(clientsocket));
}
}
/// <summary>
/// 接收方法
/// </summary>
/// <param name="clientsocket"></param>
private void receivemsg(socket clientsocket)
{
while (true)
{
//定义一个2m的缓冲区
byte[] buffer = new byte[1024 * 1024 * 2];
int length = -1;
try
{
length = clientsocket.receive(buffer);
}
catch (exception)
{
//客户端下线了
//更新在线列表
string ip = clientsocket.remoteendpoint.tostring();
addonline(ip, false);
onlinelist.remove(ip);
break;
}
if (length == 0)
{
//客户端下线了
//更新在线列表
string ip = clientsocket.remoteendpoint.tostring();
addonline(ip, false);
onlinelist.remove(ip);
break;
}
if (length > 0)
{
string info = econding.getstring(buffer, 0, length);
showmessage(info);
}
}
}
/// <summary>
/// 在线列表更新
/// </summary>
/// <param name="clientip"></param>
/// <param name="value"></param>
private void addonline(string clientip, bool value)
{
invoke(new action(() =>
{
if (value)
{
this.lst_online.items.add(clientip);
}
else
{
this.lst_online.items.remove(clientip);
}
}));
}
/// <summary>
/// 更新接收区
/// </summary>
/// <param name="info"></param>
private void showmessage(string info)
{
invoke(new action(() =>
{
this.txt_rcv.appendtext(currenttime + info + environment.newline);
}));
}
/// <summary>
/// 消息发送
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_send_click(object sender, eventargs e)
{
if (this.lst_online.selecteditem != null)
{
foreach (string item in this.lst_online.selecteditems)
{
if (onlinelist.containskey(item))
{
onlinelist[item].send(econding.getbytes(this.txt_send.text.trim()));
}
}
}
else
{
messagebox.show("请先选择要发送的对象", "发送消息");
}
}
/// <summary>
/// 群发功能
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_sendall_click(object sender, eventargs e)
{
foreach (string item in this.lst_online.items)
{
if (onlinelist.containskey(item))
{
onlinelist[item].send(econding.getbytes(this.txt_send.text.trim()));
}
}
}
}
}
7.运行效果
7.1 运行界面演示
7.2 接收消息界面演示
7.3 发送消息界面演示
7.4 群发消息演示
源码地址:
发表评论