简单的Socket通信
using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.net;
using system.net.sockets;
using system.text;
using system.threading;
using system.threading.tasks;
using system.windows.forms;
namespace socketservice
{
public partial class form1 : form
{
public form1()
{
initializecomponent();
control.checkforillegalcrossthreadcalls = false;
}
//设置服务状态
public bool servicestate = true;
//侦听
tcplistener listener;
private void form1_load(object sender, eventargs e)
{
control.checkforillegalcrossthreadcalls = false;
}
/// <summary>
/// 开始监听
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_click(object sender, eventargs e)
{
//ip
ipaddress ip = ipaddress.parse("127.0.0.1");
//侦听
listener = new tcplistener(ip,8036);
listener.start();//开始监听
//创建线程
thread mythread = new thread(listenerclient);
mythread.start();//开启线程
txtmessage.text = "开始侦听\r\n";
}
/// <summary>
/// 接收客户端消息
/// </summary>
public void listenerclient()
{
while (servicestate)
{
try
{
//接收一个client
tcpclient client = listener.accepttcpclient();
byte[] buffer = new byte[client.sendbuffersize];
//获取网络流
networkstream stream = client.getstream();
//读取数据
stream.read(buffer,0,buffer.length);
//关闭流
stream.close();
//关闭连接
client.close();
//转换格式
txtmessage.text += "来自客户端的消息:"+encoding.default.getstring(buffer).trim('\0')+"\r\n";
}
catch (exception)
{
tcpclient client = null;
}
}
}
/// <summary>
/// 关闭
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_click(object sender, eventargs e)
{
servicestate = false;
listener.stop();//停止监听
txtmessage.text += "停止监听\r\n";
}
}
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_click(object sender, eventargs e)
{
//连接
tcpclient client = new tcpclient("127.0.0.1",8036);
//转换格式
byte[] buffer = encoding.default.getbytes(txtmessage.text);
//获取流
networkstream stream = client.getstream();
//写入
stream.write(buffer, 0, buffer.length);
//刷新
stream.flush();
//关闭
stream.close();
client.close();
}
上一篇: ASP.NET Core的实时库: SignalR简介及使用
下一篇: JS实现自定义弹窗功能