C# Socket 通信

时间:2021-11-25 04:01:40

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Diagnostics;

namespace CsocketClient
{
public partial class Main : Form
{
//创建 1个客户端套接字 和1个卖力监听处事端请求的线程
Thread threadclient = null;
Socket socketclient = null;
public Main()
{
InitializeComponent();
StartPosition = FormStartPosition.CenterScreen;
//*对文本框的犯警线程操纵查抄
TextBox.CheckForIllegalCrossThreadCalls = false;

this.btnSendMessage.Enabled = false;
this.btnSendMessage.Visible = false;

// this.txtDebugInfo.Visible = false;
}

private void Form1_Load(object sender, EventArgs e)
{

}

private void btnConnection_Click(object sender, EventArgs e)
{
this.btnConnection.Enabled = false;
//界说一个套接字监听
socketclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

//获取文本框中的IP地点
IPAddress address = IPAddress.Parse("127.0.0.1");

//将获取的IP地点和端标语绑定在网络节点上
IPEndPoint point = new IPEndPoint(address, 8098);

try
{
//客户端套接字连接到网络节点上,用的是Connect
socketclient.Connect(point);
this.btnSendMessage.Enabled = true;
this.btnSendMessage.Visible = true;
this.txtMessage.Visible = true;
}
catch (Exception)
{
Debug.WriteLine("连接掉败\r\n");

this.txtDebugInfo.AppendText("连接掉败\r\n");
return;
}

threadclient = new Thread(recv);
threadclient.IsBackground = true;
threadclient.Start();
}
// 接收处事端发来信息的要领
void recv()
{
int x = 0;
//连续监听处事端发来的动静
while (true)
{
try
{
//界说一个1M的内存缓冲区,用于姑且性存储接收到的动静
byte[] arrRecvmsg = new byte[1024 * 1024];

//将客户端套接字接收到的数据存入内存缓冲区,并获取长度
int length = socketclient.Receive(arrRecvmsg);

//将套接字获取到的字符数组转换为人可以看懂的字符串
string strRevMsg = Encoding.UTF8.GetString(arrRecvmsg, 0, length);
if (x == 1)
{
this.txtDebugInfo.AppendText("处事器:" + GetCurrentTime() + "\r\n" + strRevMsg + "\r\n\n");
Debug.WriteLine("处事器:" + GetCurrentTime() + "\r\n" + strRevMsg + "\r\n\n");
}
else
{
this.txtDebugInfo.AppendText(strRevMsg + "\r\n\n");
Debug.WriteLine(strRevMsg + "\r\n\n");
x = 1;
}
}
catch (Exception ex)
{
Debug.WriteLine("长途处事器已经中断连接" + "\r\n\n");
Debug.WriteLine("长途处事器已经中断连接" + "\r\n");
break;
}
}
}

//获取当前系统时间
DateTime GetCurrentTime()
{
DateTime currentTime = new DateTime();
currentTime = DateTime.Now;
return currentTime;
}

//发送字符信息随处事真个要领
void ClientSendMsg(string sendMsg)
{
//将输入的内容字符串转换为机器可以识另外字节数组
byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(sendMsg);
//挪用客户端套接字发送字节数组
socketclient.Send(arrClientSendMsg);
//将发送的信息追加到聊天内容文本框中
Debug.WriteLine("hello...." + ": " + GetCurrentTime() + "\r\n" + sendMsg + "\r\n\n");
this.txtDebugInfo.AppendText("hello...." + ": " + GetCurrentTime() + "\r\n" + sendMsg + "\r\n\n");
}

private void btnSendMessage_Click_1(object sender, EventArgs e)
{
//挪用ClientSendMsg要领 将文本框中输入的信息发送给处事端
ClientSendMsg(this.txtMessage.Text.Trim());
this.txtMessage.Clear();
}
}
}

server

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace Csocket
{
public class Program
{
// 创建一个和客户端通信的套接字
static Socket socketwatch = null;
//界说一个调集,存储客户端信息
static Dictionary<string, Socket> clientConnectionItems = new Dictionary<string, Socket> { };

public static void Main(string[] args)
{
//界说一个套接字用于监听客户端发来的动静,包罗三个参数(IP4寻址协议,,流式连接,Tcp协议)
socketwatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//处事端发送信息需要一个IP地点和端标语
IPAddress address = IPAddress.Parse("127.0.0.1");
//将IP地点和端标语绑定到网络节点point上
IPEndPoint point = new IPEndPoint(address, 8098);
//此端口专门用来监听的

//监听绑定的网络节点
socketwatch.Bind(point);

//将套接字的监听行列队伍长度限制为20
socketwatch.Listen(20);

//卖力监听客户真个线程:创建一个监听线程
Thread threadwatch = new Thread(watchconnecting);

//将窗体线程设置为与后台同步,跟着主线程结束而结束
threadwatch.IsBackground = true;

//启动线程
threadwatch.Start();