2.Socket连接过程根据连接启动的方式以及本地套接字要连接的目标,套接字之间的连接过程可以分为三个步骤:服务器监听,客户端请求,连接确认。
(1)服务器监听:是服务器端套接字并不定位具体的客户端套接字,而是处于等待连
接的状态,实时监控网络状态。
(2)客户端请求:是指由客户端的套接字提出连接请求,要连接的目标是服务器端的
套接字。为此,客户端的套接字必须首先描述它要连接的服务器的套接字,指出服务器
端套接字的地址和端口号,然后就向服务器端套接字提出连接请求。
(3)连接确认:是指当服务器端套接字监听到或者说接收到客户端套接字的连接请求,
它就响应客户端套接字的请求,建立一个新的线程,把服务器端套接字的描述发给客户
端,一旦客户端确认了此描述,连接就建立好了。而服务器端套接字继续处于监听状态,
继续接收其他客户端套接字的连接请求。
3.代码示例:
(1)服务器端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
private static byte[] result = new byte[1024];//定义传输字节流的大小
private static int myProt = 8886;//定义端口
static Socket serSocket;//定义服务器端Socket
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");//获取服务器端IP地址
serSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serSocket.Bind(new IPEndPoint(ip, myProt));//绑定IP地址:端口
serSocket.Listen(10);//设定最多10个排队连接请求
Console.WriteLine("启动监听{0}成功", serSocket.LocalEndPoint.ToString());
Thread myThread = new Thread(Communication);//创建线程
myThread.Start();
Console.ReadLine();
}
private static void Communication()
{
while (true)
{
Socket cliSocket = serSocket.Accept();//建立一个与服务器端Socket一样的客户端Socket
cliSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));//客户端发送请求
Thread reThrea = new Thread(ReceiveMessage);//新建线程
reThrea.Start(cliSocket);
}
}
private static void ReceiveMessage(object cliSocket)
{
Socket myCliSocket = (Socket)cliSocket;
while (true)
{
try
{
int receNumber = myCliSocket.Receive(result);
Console.WriteLine("接收客户端{0}消息");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
myCliSocket.Shutdown(SocketShutdown.Both);
myCliSocket.Close();
break;
}
}
}
}
}
(2)客户端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace ConsoleApplication2
{
class Program
{
private static byte[] result = new byte[1024];
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
Socket cliSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建Socket
try
{
cliSocket.Connect(new IPEndPoint(ip, 8886));//进行连接
Console.WriteLine("连接服务器成功");
}
catch
{
Console.WriteLine("连接服务器失败,请按回车键退出!");
return;
}
int reLength = cliSocket.Receive(result);
Console.WriteLine("接收服务器消息");
for (int i = 0; i < 10; i++)
{
try
{
Thread.Sleep(1000);
string sendMessage = "client send Message Hellp" + DateTime.Now;
cliSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
Console.WriteLine("向服务器发送消息:{0}" + sendMessage);
}
catch
{
cliSocket.Shutdown(SocketShutdown.Both);
cliSocket.Close();
break;
}
}
Console.WriteLine("发送完毕,按回车键退出");
Console.ReadLine();
}
}
}