关于C#socket通信,分为同步和异步通信,本文简单介绍一下同步通信。
通信两端分别为客户端(Client)和服务器(Server):
(1)Cient:(客户端)
1:建立一个Socket对像;
2:用socket对像的Connect()方法以上面建立的EndPoint对像做为参数,向服务器发出连接请求;
3:如果连接成功,就用socket对像的Send()方法向服务器发送信息;
4:用socket对像的Receive()方法接受服务器发来的信息 ;
5:通信结束后一定记得关闭socket (未实现);
代码有待完善,只是简单的介绍客户端的创建。(会产生粘包等问题)
仅供参考仅供参考
class Client
{
Socket tcpClient;
public Client(string ip,int port) {
//创建Socket
tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//地址
IPAddress iPAddress;
if (!IPAddress.TryParse(ip,out iPAddress)) {
Console.WriteLine("IP地址有误,创建客户端失败");
return;
}
//地址:端口号
IPEndPoint point = new IPEndPoint(iPAddress,port);
try
{
tcpClient.Connect(point);//通过ip:端口号来定位一个要连接服务器
}
catch (Exception e) {
Console.WriteLine(e.Message);//如果访问的服务器未打开 抛出异常信息
return;
}
Console.WriteLine("连接成功");
}
public void Start() {
Thread th = new Thread(SendMessage);
th.Start();
th.IsBackground = true;
this.ReceiveMessage();
}
/// <summary>
/// 客户端发送信息