Client:
try
{
int port = 2000;
string host = "127.0.0.1";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipend = new IPEndPoint(ip, port);
Socket winsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
winsocket.Connect(ipend); //建立与远程主机的连接
string sendstr = "This is a socket test";
byte[] bs = Encoding.ASCII.GetBytes(sendstr); //将指定的 String 中的所有字符编码为一个字节序列
winsocket.Send(bs, bs.Length, 0); //使用指定的 SocketFlags,将指定字节数的数据发送到已连接的 Socket
//接收服务器段发回的信息
string recstr = null;
byte[] recbs = new byte[1024];
int bytes = winsocket.Receive(recbs, recbs.Length, 0);
recstr += Encoding.ASCII.GetString(recbs, 0, bytes); //将字节数组中某个范围的字节解码为一个字符串
Console.WriteLine(recstr);
winsocket.Close();
}
catch (ArgumentException e)
{
Console.WriteLine(e);
}
catch (SocketException e)
{
Console.WriteLine(e);
}
Console.Read();
Server:
try
{
int port = 2000;
string ipstr = "127.0.0.1";
IPAddress ip = IPAddress.Parse(ipstr);
IPEndPoint ipend = new IPEndPoint(ip, port);
Socket sserver = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sserver.Bind(ipend); //使 Socket 与一个终结点相关联,必须先调用 Bind,然后才能调用 Listen 方法
sserver.Listen(0); //将 Socket 置于侦听状态
Socket temp = sserver.Accept(); //为新建连接创建新的 Socket,
//在调用 Accept 方法之前,必须首先调用 Listen 方法来侦听传入的连接请求,并将侦听到的请求放入队列中
string recstr = null;
byte[] recbs = new byte[1024];
int bytes = temp.Receive(recbs, recbs.Length, 0); //从绑定的 Socket 接收指定字节数的数据,并将数据存入接收缓冲区
recstr += Encoding.ASCII.GetString(recbs,0,bytes);
Console.WriteLine(recstr);
//将信息发送成功的信息返回客户端显示
string sendstr = "OK! Successful";
byte[] sendbs = Encoding.ASCII.GetBytes(sendstr);
temp.Send(sendbs,sendbs.Length,0);
temp.Shutdown(SocketShutdown.Both);
temp.Close();
sserver.Shutdown(SocketShutdown.Both);
sserver.Close();
}
catch(ArgumentException e)
{
Console.WriteLine(e);
}
catch(SocketException e)
{
Console.WriteLine(e);
}
Console.Read();