基本信息
源码名称:C# TCP服务器代码(支持多用户链接)
源码大小:0.03M
文件格式:.rar
开发语言:C#
更新时间:2016-07-26
友情提示:(无需注册或充值,赞助后即可获取资源下载链接)
嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559
本次赞助数额为: 2 元×
微信扫码支付:2 元
×
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
源码介绍
tcp服务器目前实现的是 客户端发送什么数据,就把数据原样返回给客户端,如下图
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace TCPMultiLink
{
public partial class Form1 : Form
{
Thread listenThread = null;//监听进程
public Form1()
{
InitializeComponent();
}
private static void StartListening() //main listening thread
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 5555);//绑定5555端口
Socket newsock = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);//tcp协议
newsock.Bind(ipep);
newsock.Listen(10);
while (true)
{
Socket client = newsock.Accept();//等待TCP客户端的链接请求
ThreadClientProc p = new ThreadClientProc();
p.tempSocket = client;
Thread clientService = new Thread(new ThreadStart(p.ServiceClient));
clientService.IsBackground = true;
clientService.Start();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dr = MessageBox.Show("确定要退出程序吗?", "退出提示", MessageBoxButtons.OKCancel);
if (dr.Equals(DialogResult.OK))
{
// Application.Exit();
if (listenThread != null)
listenThread.Abort();
this.Dispose();
this.Close();
}
else
{
e.Cancel = true;
}
}
private void Form1_Load(object sender, EventArgs e)
{
//创建监听进程
listenThread = new Thread(new ThreadStart(StartListening));
listenThread.IsBackground = true;
listenThread.Start();
}
}
//客户端请求处理类
public class ThreadClientProc
{
public Socket tempSocket;
public ThreadClientProc()
{
}
public void CloseThread()
{
Thread th = Thread.CurrentThread;
th.Abort();
}
public void ServiceClient()
{
IPEndPoint newclient = (IPEndPoint)this.tempSocket.RemoteEndPoint;
NetworkStream ns = new NetworkStream(tempSocket);
StreamReader sr = new StreamReader(ns);
StreamWriter sw = new StreamWriter(ns);
//string welcome = "Welcome to tcp server!";
//sw.WriteLine(welcome);
//sw.Flush();
sw.AutoFlush = true;
char[] myReadBuffer = new char[1024];
int count;
while (true)
{
try
{
count = sr.Read(myReadBuffer, 0, myReadBuffer.Length);//读取数据
if (count > 0)
{
sw.Write(myReadBuffer, 0, count);//将原返回数据
//sw.Flush();
}
}
catch
{
break;
}
}
sw.Close();
sr.Close();
ns.Close();
}
}
}