本文实例为大家分享了C#基于Sockets类实现TCP通讯的具体代码,供大家参考,具体内容如下
最终效果
TCPClient
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 TCPClient02
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket socketSend;
private void button1_Click(object sender, EventArgs e)
{
//Create socket
socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(textBox1.Text);
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(textBox2.Text));
IDInfo idinfo = new IDInfo(); //Read ID number information
//Get the IP address and port number of the remote server
socketSend.Connect(point);
ShowMessages("Connection succeeded");
//Start a new thread and keep receiving messages sent by the server
Thread th = new Thread(ReciveMessages);
th.IsBackground = true;
th.Start();
}
private void button2_Click(object sender, EventArgs e)
{
string str = textBox3.Text.Trim();
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
socketSend.Send(buffer);
}
void ShowMessages(string str)
{
textBox4.AppendText(str + "\r\n");
}
void ReciveMessages()
{
while (true)
{
byte[] buffer = new byte[1024 * 1024 * 3];
int r = socketSend.Receive(buffer);
if (r == 0)
{
break;
}
string s = Encoding.UTF8.GetString(buffer, 0, r);
ShowMessages(socketSend.RemoteEndPoint + ":" + s);
}
}
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
}
}
TCPserver
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.Sockets;
using System.Net;
using System.Threading;
namespace TCPserver
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//创建一个负责监听的Socket
Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//创建ip地址和端口号
//IPAddress ip = IPAddress.Parse(textBox1.Text);
IPAddress ip = IPAddress.Any;
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(textBox2.Text));
//让负责监听的socket绑定ip地址和端口号
socketWatch.Bind(point);
ShowMsg("监听成功");
//设置监听队列(某一时刻连接客户端的最大数目)
socketWatch.Listen(10);
//线程执行的方法
Thread th = new Thread(Listen); //服务器开始监听
th.IsBackground = true;
th.Start(socketWatch);
}
catch
{
}
}
void ShowMsg(string str)
{
textBox3.AppendText(str + "\r\n");
}
/// <summary>
/// 等待客户端的连接 并且创建与之通信的Socket
/// </summary>
///
Socket socketSend;
void Listen(object o)
{
Socket socketWatch = o as Socket;
//负责监听的socket 来接收客户端的连接
//创建跟客户端通信的socket
while (true)
{
try
{
socketSend = socketWatch.Accept();
ShowMsg(socketSend.RemoteEndPoint.ToString() + "连接成功");
//开始一个新的线程不断接受客户端发送过来的消息
Thread th = new Thread(Recive);
th.IsBackground = true;
th.Start(socketSend);
}
catch
{
}
}
}
/// <summary>
/// 服务器不断接受客户端发送过来的消息
/// </summary>
/// <param name="o"></param>
void Recive(object o)
{
Socket socketSend = o as Socket;
while (true)
{
try
{
//客户端连接成功后,服务器应该接收客户端发来的消息
byte[] buffer = new byte[1024 * 1024 * 2];
//实际接收到的有效字节数
int bytelen = socketSend.Receive(buffer);
if (bytelen == 0)
{
break;
}
string str = Encoding.UTF8.GetString(buffer, 0, bytelen);
ShowMsg(socketSend.RemoteEndPoint + ":" + str);
}
catch
{ }
}
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
/// <summary>
/// 服务器给客户端发送消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
string str = textBox4.Text;
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
socketSend.Send(buffer);
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程网。