1.定义主机对象(IPEndPoint类的构造方法定义)
//定义IP地址
IPAddress myIP = IPAddress.Parse("127.0.0.1");
//设置端口
int port = 10000;
//定义主机对象
IPEndPoint ipEndPoint = new IPEndPoint(myIP, port);
2.主机解析(在服务器绑定与坚挺端口之前,首先要利用DNS服务器解析主机。解析主机可以用DNS类的Resolve方法)
//创建一个IPHostEntry对象
IPHostEntry myHost = new IPHostEntry();
//解析主机
myHost = Dns.Resolve("localhost");
//获取主机信息方法1
for (int i = 0; i < myHost.AddressList.Length; i++)
{
richTextBox1.AppendText("主机名:"+myHost.HostName.ToString() + "\r\n"+
"IP地址:"+myHost.AddressList[i].ToString() + "\r\n");
}
//获取主机信息方法2
textBox1.Text = Dns.GetHostName();
for (int i = 0; i < Dns.GetHostAddresses(textBox1.Text).Length; i++)
{
textBox2.Text = textBox2.Text + Dns.GetHostAddresses(textBox1.Text)[i].ToString()+" ";
}
3.端口绑定与监听(同步套接字服务器主机的绑定与端口的监听要使用Socket类的Bind方法、Listen和Accept方法。Bind方法用于绑定主机,Listen方法用于监听端口,Accept方法用于接收客户端的连接请求。)
//定义IP地址
IPAddress myIP = IPAddress.Parse("127.0.0.1");
//设置端口
int port = 10000;
//定义主机对象
IPEndPoint ipEndPoint = new IPEndPoint(myIP, port);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(ipEndPoint);
socket.Listen(50);
Socket bbb= socket.Accept();
4.发送数据(发送数据可以用Socket类的Send方法或NetworkStream类的Write方法)
Send原型:public int Send(byte[],SocketFlags);
SocketFlags成员名及其说明
成员名称 |
说明 |
DontRoute |
不使用路由表发送 |
MaxIOVectorLength |
为发送和接收数据的WSABUF结构数量提供标准值 |
None |
不对此调用使用标志 |
OutOfBand |
处理带外数据 |
Partial |
消息的部分发送或接收 |
Peek |
查看传入的消息 |
..............
Socket bbb= socket.Accept();
Byte[] bytee = new Byte[64];
string sendStr = "aaaaaaaaaaaaaaaaaaaa";
bytee = System.Text.Encoding.BigEndianUnicode.GetBytes(sendStr.ToCharArray());
bbb.Send(bytee, bytee.Length, 0);
NetworkStream类的Write方法也能发送数据。方法原型为:
public override void Write(
byte[] buffer,
int offset,
int size
)
第一个参数为字节数组,第二个参数为开始发送字节的位置,第三个参数是发送的数据的总字节数。
......................
Socket bbb= socket.Accept();
NetworkStream stre = new NetworkStream(bbb);
Byte[] ccc = new Byte[512];
string sendMessage = "aaaaaaaaaaaaaaaaa";
ccc = System.Text.Encoding.BigEndianUnicode.GetBytes(sendMessage);
stre.Write(ccc, 0, ccc.Length);
5.接收数据(可以用Socket类的Receive方法或NetworkStream类的Read方法。)
a) Receive方法接收数据
.....................
Socket bbb= socket.Accept();
......................
Byte[] ccc = new Byte[512];
//Receive方法接收数据
bbb.Receive(ccc, ccc.Length, 0);
string rece = System.Text.Encoding.BigEndianUnicode.GetString(ccc);
richTextBox1.AppendText(rece + "\r\n");
b) Read方法接收数据
.....................
Socket bbb= socket.Accept();
......................
NetworkStream stre = new NetworkStream(bbb);
Byte[] ccc = new Byte[512];
stre.Read(ccc, 0, ccc.Length);
string readMessage = System.Text.Encoding.BigEndianUnicode.GetString(ccc);