Socket网络编程
目录
一、基本概念
二、服务端创建步骤
三、客户端创建步骤
四、实例:多人聊天
TCP:(Transmission Control Protocal)可靠的数据传输的高层协议 (三次握手)
UDP协议:数据包协议 视频传输 快速 无连接 数据报协议 (不可靠)
IP地址:唯一地标识 Internet 上的每台电脑
端口号:同一机器上的不同通信进程的标识
IPEndPoint:网络地址和端口号的组合统称为端点
Socket三要素: IP地址+端口号+通信协议
服务端:是为其他电脑提供服务的。好比超市的服务台,有什么事儿都找服务台帮助协商解决。相当于通信公司的总机,
和谁通电话要先通过总机来转接。
1、实例化一个Socket对象,负责监听客户端连接。(总机)
Socket soctWatch = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
2、使用Bind()方法绑定一个负责监听的端口号(为总机绑定端口号)
IPAddress ip = IPAddress.Any;
//要监听的端口号
int port = int.Parse(txtPort.Text.Trim());
//创建端点
IPEndPoint ipPoint = new IPEndPoint(ip, port);
3、使用Listen()方法监听其他客户端的连接
4、如果有一个客户端连入了该端口,服务端使用Accept方法接收客户端的连接
5、服务端会创建一个Socket对象,专门和这个客户端通信(一对一服务)
6、客户端就可以向服务端发送消息
7、服务端接收消息并显示
8、服务端也可以向客户端发送消息
Windows+R:在运行中输入cmd,
然后在dos界面中输入:你的ip地址 你服务器开放的端口号。例:Telnet 192.168.119.100 5000
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;//允许线程间操作
}
private void button1_Click(object sender, EventArgs e)
{
//1、创建一个负责监听的Socket对象
Socket soctWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//2、绑定监听端点,即所有的IP地址都可以连接我的服务端
IPAddress ip = IPAddress.Any;//监听的IP地址为所有IP
//要监听的端口号
int port = int.Parse(textPort.Text.Trim());
//创建端点
IPEndPoint ipPoint = new IPEndPoint(ip, port);
//使socket与端点连接
soctWatch.Bind(ipPoint);
//开始监听
soctWatch.Listen(10);//backlog挂起连接队列的最大程度
ShowMsg("开始监听!");
//创建一个线程进行客户端连接,避免假死
Thread th = new Thread(ListenClient);
th.IsBackground = true;
th.Start(soctWatch);
}
public void ListenClient(object t)
{
Socket sc = t as Socket;
while (true)
{
//创建一个Socket对象,接收客户端连接
Socket soctClient = sc.Accept();
//显示
ShowMsg(soctClient.RemoteEndPoint + ":监听成功"); //RemoteEndPoint获取远程终结点
//接收用户的消息
//为避免界面卡死,开一个新线程处理用户发送的数据
Thread th = new Thread(ReceiveMsg);
th.IsBackground = true;
th.Start(soctClient);
}
}
public void ReceiveMsg(object b)
{
Socket sc = b as Socket;//将object类型转化成Socket对象
byte[] buffer = new byte[1024 * 1024];
while (true)
{
try
{
int count = sc.Receive(buffer);//接收方法
if (count == 0)//如果不再有字符过来
{
break;
}
string s = Encoding.UTF8.GetString(buffer);//将接收到的字节数组转换成字符串
ShowMsg(sc.RemoteEndPoint + ":" + s + "\r\t");//RemoteEndPoint:远程客户端的ip和端口号
Array.Clear(buffer, 0, buffer.Length);//清空!!
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
}
private void ShowMsg(string str)
{
textShow.AppendText(str + "\r\t");
}
}
1、创建一个客户端Socket对象,负责监听服务端连接
scClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
2、连接服务器
scClient.Connect(endPoint);
3、客户端向服务器发送消息
//将发送区中文本框的内容转换成字节数组
byte[] buffer = new byte[1024];
buffer= Encoding.UTF8.GetBytes(textSend.Text);
//给服务器发送消息
scClient.Send(buffer);
public partial class Form1 : Form
{
Socket scClient; //客户端Socket
public Form1()
{
InitializeComponent();
//允许线程间操作
Control.CheckForIllegalCrossThreadCalls = false;
}
private void btnConnect_Click(object sender, EventArgs e)
{
//创建一个客户端Socket对象,连接服务器
scClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//要连接到服务器的IP地址
string strIp = textIP.Text.Trim();
IPAddress ip = IPAddress.Parse(strIp); //IP地址
int port = Convert.ToInt32(textPort.Text.Trim()); //端口号
IPEndPoint endPoint = new IPEndPoint(ip, port); //端点
//连接服务器
scClient.Connect(endPoint);
ShowMessage("连接成功!");
//开启一个线程接收服务器端发送的数据
Thread th = new Thread(ReceiveFromServer);
th.IsBackground = true;
th.Start();
}
///
/// 接收从服务器端发来的消息
///
private void ReceiveFromServer()
{
while (true)
{
try
{
//创建字节数组
byte[] buffer = new byte[1024 * 1024];
//接收服务器端发送过来的数据,存到buffer数组中
int n = scClient.Receive(buffer);
if (n == 0) //没有数据
{
break;
}
//将接收到的数据转换成字符串
string s = Encoding.UTF8.GetString(buffer);
ShowMessage(scClient.RemoteEndPoint + ":" + s);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
}
///
/// 向文本框中追加信息,实时显示通信内容
///
///
private void ShowMessage(string str)
{
textMsg.AppendText(str + "\r\n");
}
///
/// 客户端向服务器发送消息
///
///
///
private void btnSend_Click(object sender, EventArgs e)
{
//将发送区中文本框的内容转换成字节数组
byte[] buffer = new byte[1024];
buffer= Encoding.UTF8.GetBytes(textSend.Text);
//给服务器发送消息
scClient.Send(buffer);
buffer = null;//????
}
}
......