socket通讯
我简单的查询了socket的含义。socket的本质是编程接口,也就是API,是对TCP/IP的封装。可以通过这个接口让两个应用程序之间实现通讯。
那么应用程序和应用程序之间是怎么实现通讯的呢?
1.首先服务器与socket进行绑定
2.将socket加入到监听对列,阻塞进程开始监听
3.客户端与socket进行绑定
4.建立连接用的socket,将需要进行通讯的网络端点绑定在socket上
5.打开连接
6.使用send方法和receive方法向服务器发送或接收信息
7.关闭连接
服务端:
static Socket sockWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
static void Main(string[] args)
{
int Port = 6000;
string host = "0.0.0.0";
IPAddress address = IPAddress.Parse(host);
IPEndPoint endpoint = new IPEndPoint(address, Port);
sockWatch.Bind(endpoint);//绑定socket
sockWatch.Listen(10);//监听队列
Console.WriteLine("服务端开始监听");
WatchConnecting();
}
public static void WatchConnecting()
{
Socket sockConnection = sockWatch.Accept();//阻塞当前线程,开始监听
Console.WriteLine("与客户端的连接已建立");
Console.Write("正在等待客户端发送信息");
Thread.Sleep(200);
for (int i = 0; i < 3; i++)
{
Console.Write(".");
}
MsgShow(sockConnection);
Console.WriteLine();
Console.WriteLine("是否发送数据?Y/N");
string msg = Console.ReadLine();
if (msg=="Y")
{
Console.WriteLine("请输入您要发送的数据:");
string data = Console.ReadLine();
SendMsg(data, sockConnection);
}
else
{
Console.Write("准备结束通讯");
for (int i = 0; i < 3; i++)
{
Console.Write(".");
Thread.Sleep(100);
}
sockConnection.Close();
sockWatch.Close();
}
}
public static void MsgShow(Socket sockConnection)
{
StringBuilder str = new StringBuilder();
byte[] data = new byte[4496] ;
int result = sockConnection.Receive(data, data.Length, 0);
str.Append(Encoding.ASCII.GetString(data,0,result));
Console.WriteLine("接收到来自客户端的数据:" + str);
}
public static void SendMsg(object sender,Socket sockConnection)
{
byte[] data = Encoding.ASCII.GetBytes(sender.ToString());//将数据转换为字节数据
sockConnection.Send(data, data.Length, 0);//发送数据
Console.WriteLine("数据已成功发送");
}
客户端:
//创建Socket实例
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
byte[] MsgBuffer = new byte[4696];
static void Main(string[] args)
{
//客户端
int port = 6000;//端口
string host = "106.13.84.189";//服务器ip地址
IPAddress ip = IPAddress.Parse(host);//将ip字符串转为ip地址实例
IPEndPoint ipe = new IPEndPoint(ip, port);//网络端点
Program pr = new Program();
pr.clientSocket.Connect(ipe);
Console.WriteLine("通讯已经打开!");
Console.WriteLine("请输入您要发送的数据:");
string data = Console.ReadLine();
send(data, pr.clientSocket);
Console.WriteLine("接收到的数据:{0}", receive(pr.clientSocket));
//pr.Connect(ip, port);//开始连接
//Console.WriteLine("连接已建立");
//pr.Send("hello server");
//pr.ReceiveData();
}
/// <summary>
/// 发送数据
/// </summary>
/// <param name="data"></param>
public static void send(string data,Socket clientSocket)
{
byte[] databyte = Encoding.ASCII.GetBytes(data);
clientSocket.Send(databyte, databyte.Length, 0);
}
public static string receive(Socket clientSocket)
{
string str = "";
byte[] strbytes = new byte[7071];
int recbyte = clientSocket.Receive(strbytes, strbytes.Length, 0);
str += Encoding.ASCII.GetString(strbytes, 0, recbyte);
return str;
}
/// <summary>
/// 异步连接
/// </summary>
/// <param name="ip">服务器ip</param>
/// <param name="port">端口</param>
public void Connect(IPAddress ip, int port)
{
this.clientSocket.BeginConnect(ip, port, new AsyncCallback(ConnectCallback), this.clientSocket);
}
private void ConnectCallback(IAsyncResult ar)
{
//try
//{
Socket handler = (Socket)ar.AsyncState;
handler.EndConnect(ar);
//}
//catch (Exception e)
//{
// throw;
//}
}
/// <summary>
/// 发送信息
/// </summary>
/// <param name="data">发送内容</param>
public void Send(string data)
{
Send(System.Text.Encoding.UTF8.GetBytes(data));
}
private void Send(byte[] byteData)
{
//try
//{
int length = byteData.Length;
byte[] head = BitConverter.GetBytes(length);
byte[] data = new byte[head.Length + byteData.Length];
Array.Copy(head, data, head.Length);
Array.Copy(byteData, 0, data, head.Length, byteData.Length);
this.clientSocket.BeginSend(data, 0, data.Length, 0, new AsyncCallback(SendCallback), this.clientSocket);
//}
//catch (Exception)
//{
// throw;
//}
}
private void SendCallback(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState;
handler.EndSend(ar);
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 接收信息
/// </summary>
public void ReceiveData()
{
this.clientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallback), null);
}
private void ReceiveCallback(IAsyncResult ar)
{
try
{
int REnd = clientSocket.EndReceive(ar);
if (REnd > 0)
{
byte[] data = new byte[REnd];
Array.Copy(MsgBuffer, 0, data, 0, REnd);
clientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallback), null);
}
else
{
dispose();
}
}
catch (Exception)
{
throw;
}
}
private void dispose()
{
try
{
this.clientSocket.Shutdown(SocketShutdown.Both);
this.clientSocket.Close();
}
catch (Exception)
{
throw;
}
}
实现效果:
刚刚开始接触socket,还有很多东西不懂,日后慢慢研究会更新文章