一、服务器端
步骤:
- 创建服务器端Socket: server;
- 给server绑定ip地址和端口号,server.Bind()方法;
- 开始监听客户端连接请求,server.Listen()方法;
- 接受客户端的连接请求,得到一个Socket对象与客户端通信:client;
- 与客户端通信,即收发信息,client.Send()和client.Receive()方法。
- 通信结束后,要关闭Socket,先关闭通信用的client,在关闭server。
class Program
{
static void Main()
{
try
{
int port = 2000;
string host = "127.0.0.1";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);//创建一个Socket类
server.Bind(ipe);//绑定2000端口
server.Listen(0);//开始监听
Console.WriteLine("Wait for connect");
Socket client = server.Accept();//为新建连接创建新的Socket。
Console.WriteLine("Get a connect");
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = client.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
Console.WriteLine("Server Get Message:{0}", recvStr);//把客户端传来的信息显示出来
string sendStr = "Ok!Client Send Message Sucessful!";
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
client.Send(bs, bs.Length, 0);//返回客户端成功信息
client.Close();
server.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("Press Enter to Exit");
Console.ReadLine();
}
}
二、客户端
步骤:
- 创建服务器端Socket: client;
- 请求连接服务器,client.Connect()方法;
- 与服务器通信。
class Program
{
static void Main()
{
try
{
int port = 2000;
string host = "127.0.0.1";
IPAddress ip = IPAddress.Parse(host);
IPEndPoint ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
Socket client= new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);//创建一个Socket
Console.WriteLine("Conneting...");
client.Connect(ipe);//连接到服务器
string sendStr = "hello!This is a socket test";
byte[] bs = Encoding.ASCII.GetBytes(sendStr);
Console.WriteLine("Send Message");
client.Send(bs, bs.Length, 0);//发送测试信息
string recvStr = "";
byte[] recvBytes = new byte[1024];
int bytes;
bytes = client.Receive(recvBytes, recvBytes.Length, 0);//从服务器端接受返回信息
recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
Console.WriteLine("Client Get Message:{0}", recvStr);//显示服务器返回信息
client.Close();
}
catch (ArgumentNullException e)
{
Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
Console.WriteLine("Press Enter to Exit");
Console.ReadLine();
}
}
三、
- 只要连接通了,可以先发信息,在接收信息,也可以反过来。
- Socket的Send()和Receive()方法可以设置超时时间,默认为0,表示无期限,设置为-1也是无期限。不设置超时时间,当发送不出去或接受不到信息,这两个方法会无期限的阻塞(卡)住。
Socket client = server.Accept(); client.SendTimeout = 5000;//发送超时时间为5s client.ReceiveTimeout = 5000;//接收超时时间为5s