socket服务端【记录一下】

新建一个类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
public static class SocketTest
{
private static Encoding encode = Encoding.Default;
///
/// 监听请求
///
///
public static void Listen(int port)
{
Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listenSocket.Bind(new IPEndPoint(IPAddress.Any, port));
listenSocket.Listen(100);
Console.WriteLine(“监听端口: " + port + " 监听开始”);
while (true)
{
Socket acceptSocket = listenSocket.Accept();
string receiveData = Receive(acceptSocket, 5000); //5 seconds timeout.
Console.WriteLine(“收到信息:” + receiveData);
acceptSocket.Send(encode.GetBytes(“ok”));
DestroySocket(acceptSocket); //import
}
}
///
/// 发送数据
///
///
///
///
///
public static string Send(string host, int port, string data)
{
string result = string.Empty;
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(host, port);
clientSocket.Send(encode.GetBytes(data));
Console.WriteLine(“Send:” + data);
result = Receive(clientSocket, 5000 * 2); //5*2 seconds timeout.
Console.WriteLine(“Receive:” + result);
DestroySocket(clientSocket);
return result;
}
///
/// 接收数据
///
///
///
///
private static string Receive(Socket socket, int timeout)
{
string result = string.Empty;
socket.ReceiveTimeout = timeout;
List data = new List();
byte[] buffer = new byte[1024];
int length = 0;
try
{
while ((length = socket.Receive(buffer)) > 0)
{
for (int j = 0; j < length; j++)
{
data.Add(buffer[j]);
}
if (length < buffer.Length)
{
break;
}
}
}
catch { }
if (data.Count > 0)
{
result = encode.GetString(data.ToArray(), 0, data.Count);
}
return result;
}
///
/// 销毁Socket对象
///
///
private static void DestroySocket(Socket socket)
{
if (socket.Connected)
{
socket.Shutdown(SocketShutdown.Both);
}
socket.Close();
}
}
}

主程序监听

using Amqp.Types;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;

namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
SocketTest.Listen(8810);
}
}
}

启动监听服务

打开cmd测试
测试程序正常监听

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值