基本信息
源码名称:C# Socket的TCP通讯示例(入门级)
源码大小:0.10M
文件格式:.zip
开发语言:C#
更新时间:2017-12-07
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
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 MySocket
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//防止新线程调用主线程卡死
CheckForIllegalCrossThreadCalls = false;
}
Socket sck = null;
Thread thread = null;
//点击开启服务端监听
private void btnServer_Click(object sender, EventArgs e)
{
//创建一个Socket实例
//第一个参数表示使用ipv4
//第二个参数表示发送的是数据流
//第三个参数表示使用的协议是Tcp协议
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//获取ip地址局域网使用 ipv4,广域网使用外网IP
IPAddress ip = IPAddress.Parse(txtIP.Text);
//创建一个网络通信节点,这个通信节点包含了ip地址,跟端口号。
//这里的端口我们设置为1029,这里设置大于1024,为什么自己查一下端口号范围使用说明。
IPEndPoint endPoint = new IPEndPoint(ip, int.Parse(txtPort.Text));
//Socket绑定网路通信节点
sck.Bind(endPoint);
//设置监听队列
sck.Listen(10);
ShowMsg("开启监听!");
//开启一个新线程,放入Socket服务监听
Thread thread = new Thread(JtSocket);
//设置为后台线程
thread.IsBackground = true;
thread.Start();
}
Socket accSck = null;
//Socket服务监听函数
void JtSocket()
{
while (true)//注意该循环,服务端要持续监听,要不然一个客户端链接过后就无法链接第二个客户端了。
{
//创建一个接收客户端通信的Socket
accSck = sck.Accept();
//如果监听到客户端有链接,则运行到下一部,提示,链接成功!
ShowMsg("链接成功!");
}
}
//消息框里面数据
void ShowMsg(string str)
{
string Ystr = "";
if (txtChat.Text != "")
{
Ystr = txtChat.Text "\r\n";
}
txtChat.Text = Ystr str;
}
/// <summary>
/// 向客户端发消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSend_Click(object sender, EventArgs e)
{
string SendMsg = txtMsg.Text;
if (SendMsg != "")
{
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(SendMsg); //将要发送的数据,生成字节数组。
accSck.Send(buffer);
ShowMsg("向客户端发送了:" SendMsg);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}