TCP应用编程--套接字C#实现
套接字之间的连接过程可以分为三个步骤:
1、服务器监听
2、客户端请求
3、连接确认
Ø服务器监听:是指服务器套接字并不定位具体的客户端套接字,而
是处于等待连接的状态,实时监控网络状态。
Ø客户端请求:是指由客户端的套接字提出连接请求,要连接的目标是服务器的套接字。为此,客户端的套接字必须首先描述它要连接的服务器的套接字,指出服务器套接字的地址和端口号,然后再向服务器套接字提出连接请求。
Ø连接确认:是指当服务器套接字监听到客户端套接字的连接请求时,它就响应客户端套接字的请求,把服务器套接字的信息发给客户端,一旦客户端确认了此信息,连接即可建立。而服务器套接字继续监听其他客户端套接字的连接请求。
一、服务器端程序
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Diagnostics;
//服务器程序
namespace SocketServer
{
class Program
{
private static byte[] result = new Byte[1024];
private static int myprot = 8889;
static Socket serverSocket;
static void Main(string[] args)
{
//服务器IP地址
IPAddress ip = IPAddress.Parse("127.0.0.1");
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(ip, myprot));
serverSocket.Listen(10);
Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());
//通过clientsocket发送数据
Thread myThread = new Thread(ListenClientConnect);
myThread.Start();
Console.ReadLine();
}
/// <summary>
/// 接收连接
/// </summary>
private static void ListenClientConnect()
{
while (true)
{
Socket clientsocket = serverSocket.Accept();
clientsocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
Thread receiveThread = new Thread(ReceiveMessage);
receiveThread.Start(clientsocket);
}
}
/// <summary>
/// 接收信息
/// </summary>
/// <param name="clientSocket">包含客户机信息的套接字</param>
private static void ReceiveMessage(Object clientSocket)
{
Socket myClientSocket = (Socket)clientSocket;
while (true)
{
try
{
//通过clientsocket接收数据
int receiveNumber = myClientSocket.Receive(result);
Console.WriteLine("接收客户端{0}消息{1}",myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, receiveNumber));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
myClientSocket.Shutdown(SocketShutdown.Both);
myClientSocket.Close();
break;
}
}
}
}
}
二、客户端程序
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
//客户端程序
namespace SocketClient
{
class Program
{
private static byte[] result = new Byte[1024];
static void Main(string[] args)
{
//服务器IP地址
IPAddress ip = IPAddress.Parse("127.0.0.1");
Socket clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
try
{
clientSocket.Connect(new IPEndPoint(ip, 8889));
Console.WriteLine("连接服务器成功");
}
catch
{
Console.WriteLine("连接服务器失败,请按回车键退出");
return;
}
//通过clientSocket接收数据
int receiveLength = clientSocket.Receive(result);
Console.WriteLine("接收服务器消息:{0}",Encoding.ASCII.GetString(result, 0, receiveLength));
// 通过clientSocket发送数据
for (int i = 0; i < 10; i++)
{
try
{
Thread.Sleep(1000);
string sendMessage = "client send Message Hello" + DateTime.Now;
clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
Console.WriteLine("向服务器发送消息:{0}", sendMessage);
}
catch
{
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
break;
}
}
Console.WriteLine("发送完毕,按回车键退出");
Console.ReadLine();
}
}
}
三、运行结果如下