创建服务器:
①:创建一个用于监听连接的Socket对象;
②:用指定的端口号和服务器的Ip建立一个EndPoint对象;
③:用Socket对象的Bind()方法绑定EndPoint;
④:用Socket对象的Listen()方法开始监听;
⑤:接收到客户端的连接,用Socket对象的Accept()方法创建一个新的用于和客户端进行通信的Socket对象;
⑥:通信结束后一定记得关闭Socket。
//1.创建服务器端
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
//2.创建IP与端口
IPAddress iP = IPAddress.Parse(ip);
IPEndPoint endPoint = new IPEndPoint(iP, int.Parse(8080));
//3.将端口放到服务器中
server.Bind(endPoint);
//4.开始监听
//同一时刻允许同时加入链接的最大数量
server.Listen(20);
listBox1.Items.Add("服务器已经成功开启!");
//5.等待链接
while (true)
{
//接受接入的一个客户端
connectClient = server.Accept();
if (connectClient != null)
{
string info = connectClient.RemoteEndPoint.ToString();
clientList.Add(info, connectClient);
listBox1.Items.Add(info + "加入服务器!");
string msg = DateTime.Now + "你已经成功进入8080";
SendMsg(msg);
//每有一个客户端接入,需要有一个线程进行服务
Thread threadclient = new Thread(ReciveMsg);
threadclient.IsBackground = true;
//设置这个线程中的通信对象时对应的socket与客户端socket进行通信
threadclient.Start(connectClient);
}
}
void ReciveMsg(object o)
{
Socket client = o as Socket;
while (true)
{
try
{
byte[] arrMsg = new byte[1024 * 1024];
int length = client.Receive(arrMsg);
if (length > 0)
{
string recMsg = Encoding.UTF8.GetString(arrMsg, 0, length);
IPEndPoint endPoint = client.RemoteEndPoint as IPEndPoint;
listBox1.Items.Add(DateTime.Now + "[" + endPoint.Port.ToString() + "]" + recMsg);
SendMsg("[" + endPoint.Port.ToString() + "]" + recMsg);
}
}
catch (Exception)
{
client.Close();
clientList.Remove(client.RemoteEndPoint.ToString());
}
}
}
创建客户端
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace _01socket客户端
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
Socket client;
private void button1_Click(object sender, EventArgs e)
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
IPAddress ip = IPAddress.Parse(textBox1.Text);
IPEndPoint endpoint = new IPEndPoint(ip, int.Parse(textBox2.Text));
client.Connect(endpoint);
Thread thread = new Thread(ReciveMsg);
thread.IsBackground = true;
thread.Start(client);
}
/// <summary>
/// 接受数据
/// </summary>
/// <param name="o"></param>
void ReciveMsg(object o)
{
client = o as Socket;
while (true)
{
byte[] arrlist = new byte[1024 * 1024];
int length = client.Receive(arrlist);
string msg = DateTime.Now + Encoding.UTF8.GetString(arrlist, 0, length);
listBox1.Items.Add(msg);
}
}
void SendMsg(string msg)
{
byte[] arrmsg = Encoding.UTF8.GetBytes(msg);
client.Send(arrmsg);
}
private void button2_Click(object sender, EventArgs e)
{
if (textBox3.Text != "")
{
SendMsg(textBox3.Text);
textBox3.Text = "";
}
}
}
}