Socket同步编程

服务器端代码

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

namespace Server
{
public class Server
{
private static string data = null;

/// <summary>
/// 开始监听
/// </summary>
public static void StartListening()
{
byte[] buffer = new byte[1024];//用来缓冲

//设置服务器端Socket
IPHostEntry ipHostInfo = Dns.GetHostByName(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1111);


Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//实例化一个Socket
listener.Bind(ipEndPoint);//绑定
listener.Listen(10);//设置最大监听数量
while (true)
{
Console.WriteLine("服务器正等待客户端的连接");
Socket server = listener.Accept();//会一直阻塞,直到有客户端连接
while (true)
{
int rec = server.Receive(buffer);
data += Encoding.ASCII.GetString(buffer, 0, rec);
if(data.IndexOf("<EOF>")>-1)
{
break;
}
}
Console.WriteLine("接收到的客户端数据是:{0}",data);

//将收到的数据再发给客户端
buffer = Encoding.ASCII.GetBytes(data);
server.Send(buffer);
server.Shutdown(SocketShutdown.Both);
server.Close();

}

}
static void Main(string[] args)
{
StartListening();
}
}
}



客户端代码

sing System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace Client
{
class Client
{
public static void StartClient()
{
byte[] buffer = new byte[1024];
//服务器的地址
IPAddress ipAddress = IPAddress.Parse("114.214.60.253");
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1111);

//连接服务器
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(ipEndPoint);

//发送数据
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");
int send=client.Send(msg);

//接受数据
int rec = client.Receive(buffer);
Console.WriteLine("客户端接收到的数据是:{0}",Encoding.ASCII.GetString(buffer,0,rec));
Console.Read();
}
static void Main(string[] args)
{
StartClient();
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值