效果图:客户端与服务端交互
服务端
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Server
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket remote = null;
private void btnConnect_Click(object sender, EventArgs e)
{
//异步启动服务端
Task.Run(() =>
{
Boolean running = true;
//============================================================================//
// 1、socket服务地址和监听端口
//============================================================================//
// socket服务地址
string host = "127.0.0.1";
// socket服务端口
int port = 21000;
// 将将IP地址字符串转换为IPAddress对象
IPAddress ip = IPAddress.Parse(host);
// 终结点EndPoint
IPEndPoint ipe = new IPEndPoint(ip, port);
//============================================================================//
// 2、创建socket连接服务端并监听端口
//============================================================================//
//创建TCP Socket对象
//绑定EndPoint对象(地址)