using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
{
class Program
{
/// <summary>
/// 发送数据
/// </summary>
/// <param name="s">发送数据的套接字</param>
/// <param name="data">缓冲区</param>
/// <returns></returns>
private static int SendData(Socket s, byte[] data)
{
int total = 0;
int size = data.Length;
int dataleft = size;
int sent;
{
sent = s.Send(data, total, SocketFlags.None);
total += sent;
dataleft -= sent;
}
return total;
}
/// <summary>
/// 接受数据
/// </summary>
/// <param name="s">接受数据的套接字</param>
/// <param name="size"></param>
/// <returns></returns>
private static byte[] ReceiveData(Socket s, int size)
{
int total = 0;
int dataleft = size;
byte[] data = new byte[size];
int recv;
{
recv = s.Receive(data, total, dataleft, 0);
if (recv == 0)
{
data = Encoding.ASCII.GetBytes("exit");
break;
}
total += recv;
dataleft -= recv;
}
return data;
}
static void Main(string[] args)
{
//定义一个服务器
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//绑定并且开始监听
newsock.Bind(ipep);
newsock.Listen(10);
//接受客户端的连接请求
Socket client = newsock.Accept();
IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}", newclient.Address, newclient.Port);
string welcome = "Welcome to my test server";
data = Encoding.ASCII.GetBytes(welcome);
int sent = SendData(client, data);//调用发送信息函数
{
data = ReceiveData(client, 9);
Console.WriteLine(Encoding.ASCII.GetString(data));
}
Console.WriteLine("Disconnected from {0}", newclient.Address);
client.Close();
newsock.Close();
}
}
}
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
{
class Program
{
private static int SendData(Socket s, byte[] data)
{
int total = 0;
int size = data.Length;
int dataleft = size;
int sent;
{
sent = s.Send(data, total, dataleft, SocketFlags.None);
total += sent;
dataleft -= sent;
}
return total;
}
{
int total = 0;
int dataleft = size;
byte[] data = new byte[size];
while (total < size)
{
}
}
{
}
}
}