winform socket编程之TCPListener
运行结果:



服务端代码
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 SocketServer
{
public partial class Form1 : Form
{
private List<TcpClient> clientList=new List<TcpClient>();///保存客户连接socket
private TcpListener tcpListener;///监听类 public Form1()
{
InitializeComponent();
} private void button3_Click(object sender, EventArgs e)
{
tcpListener = new TcpListener(IPAddress.Any, );//监听3000端口
tcpListener.Start();//开始监听
Thread listenThread = new Thread(new ThreadStart(ListenForClients));///新建线程来处理新的客户端连接
listenThread.Start(); } /// <summary>
/// 处理客户端连接线程
/// </summary>
private void ListenForClients()
{
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
clientList.Add(client);
listBox2.BeginInvoke(new Action(()=>{listBox2.Items.Add(client.Client.RemoteEndPoint.ToString());}));
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client); }
} /// <summary>
/// 读客户端数据
/// </summary>
/// <param name="client"></param>
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[];
int bytesRead;
while (true)
{
bytesRead = ;
try
{
//blocks until a client sends a message,每个线程在这一句时会中断一下,等待客户端有数据传进来后再往下执行
bytesRead = clientStream.Read(message, , );
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == )
{
//the client has disconnected from the server
break;
} //message has successfully been received
UTF8Encoding utf8 = new UTF8Encoding();
System.Diagnostics.Debug.WriteLine(utf8.GetString(message, , bytesRead));
///线程里修改UI界面的内容要用invoke方法和委托
listBox1.Invoke(new Action(() => { listBox1.Items.Add(utf8.GetString(message, , bytesRead)); }));
} //tcpClient.Close();//不要关闭
} /// <summary>
/// 向所有客户端发送
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
foreach (var item in clientList)
{
NetworkStream stream=item.GetStream();
stream.Write(UTF8Encoding.UTF8.GetBytes(this.textBox1.Text), , UTF8Encoding.UTF8.GetBytes(this.textBox1.Text).Length);
}
}
}
}
客户端代码
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 EdoecSpeaker
{
public partial class Form1 : Form
{
TcpClient client;
public Form1()
{
InitializeComponent();
} /// <summary>
/// 连接服务器
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
if (client==null)
{
client = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), );
client.Connect(serverEndPoint);
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
//clientStream.Flush();
} /// <summary>
/// 接收消息
/// </summary>
/// <param name="client"></param>
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream(); byte[] message = new byte[];
int bytesRead; while (true)
{
bytesRead = ; try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, , );
}
catch
{
//a socket error has occured
break;
} if (bytesRead == )
{
//the client has disconnected from the server
break;
} //message has successfully been received
UTF8Encoding utf8 = new UTF8Encoding();
System.Diagnostics.Debug.WriteLine(utf8.GetString(message, , bytesRead));
listBox1.Invoke(new Action(() => { listBox1.Items.Add(utf8.GetString(message, , bytesRead)); }));
}
//tcpClient.Close();
} /// <summary>
/// 发送消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_Click(object sender, EventArgs e)
{
NetworkStream clientStream = client.GetStream();
clientStream.Write(UTF8Encoding.UTF8.GetBytes(this.textBox1.Text), , UTF8Encoding.UTF8.GetBytes(this.textBox1.Text).Length);
}
}
}
winform socket编程之TCPListener的更多相关文章
- [深入浅出WP8.1(Runtime)]Socket编程之UDP协议
13.3 Socket编程之UDP协议 UDP协议和TCP协议都是Socket编程的协议,但是与TCP协议不同,UDP协议并不提供超时重传,出错重传等功能,也就是说其是不可靠的协议.UDP适用于一次只 ...
- iPhone socket 编程之BSD Socket篇
iPhone socket 编程之BSD Socket篇 收藏在进行iPhone网络通讯程序的开发中,不可避免的要利用Socket套接字.iPhone提供了Socket网络编程的接口CFSocket, ...
- 老雷socket编程之websocket实现
老雷socket编程之websocket实现 我们主要实现私聊和群聊两个功能,要在web端实现想微信QQ那样的即时通讯的功能,我们需要了解一下websocket.websocket是一种可以双向通讯的 ...
- 老雷socket编程之PHP利用socket扩展实现聊天服务
老雷socket编程之PHP利用socket扩展实现聊天服务 socket聊天服务原理 PHP有两个socket的扩展 sockets和streamssockets socket_create(AF_ ...
- PHP Socket 编程之9个主要函数的使用之测试案例
php的socket编程算是比较难以理解的东西吧,不过,我们只要理解socket几个函数之间的关系,以及它们所扮演的角色,那么理解起来应该不是很难了,在笔者看来,socket编程,其实就是建立一个网络 ...
- C#编程 socket编程之TcpClient,TcpListener,UdpClient
应用程序可以通过 TCPClient.TCPListener 和 UDPClient 类使用传输控制协议 (TCP) 和用户数据文报协议 (UDP) 服务.这些协议类建立在 System.Net.So ...
- winform网络编程之TcpClient类,TcpListener类和UdpClient类
TcpClient类和TcpListener类 (1)TcpClient的用途: 用于在同步阻止模式下通过网络来链接.发送和接受流数据,在此情况下,必须有侦听此连接的请求,而侦听的任务就交给TcpLi ...
- Python socket编程之二:【struct.pack】&【struct.unpack】
import struct """通过 socket 的 send 和 recv 只能传输 str 格式的数据""" "" ...
- Linux系统编程(37)—— socket编程之UDP服务器与客户端
典型的UDP客户端/服务器通讯过程: 编写UDP Client程序的步骤 1.初始化sockaddr_in结构的变量,并赋值.这里使用"8888"作为连接的服务程序的端口,从命令行 ...
随机推荐
- c语言中字符串函数的使用
#include<stdio.h> #include<string.h> /* char s1[]="I am a student"; char s2[20 ...
- SourceTree 基本介绍
Git的服务器端: 最出名的是GitHub,但是不能创建私有仓库,创建私有得需要Money Bitbucket:可以创建私有数据库,但是速度太慢,太消磨激情了 如果既想创建私有又想要激情,那只能自己搭 ...
- Spring定时任务有时候会莫名奇妙的终止?
最近在是使用Spring配置定时定时任务(基于xml配置使用spring自带的定时任务),一开始使用没什么问题当使用久了就会出现有些定时任务自动停止了.(关于如何使用以及如何它的原理是啥,这里不进行阐 ...
- 使用Mybatis进行多表联查操作
(1)增加一个测试数据库shop_order,sql语句如下: CREATE DATABASE `shop_order`; USE `shop_order`; CREATE TABLE `t_user ...
- Java SpringMVC 定时任务
1.web.xml 2.spring-mvc.xml <?xml version="1.0" encoding="UTF-8"?> <bean ...
- 浅谈Async/Await
概要 在很长一段时间里面,FE们不得不依靠回调来处理异步代码.使用回调的结果是,代码变得很纠结,不便于理解与维护,值得庆幸的是Promise带来了.then(),让代码变得井然有序,便于管理.于是我们 ...
- 我是这样学习使用google学术的
本科期间一直在cnki上面检索论文,随着科研能力的需要,部分论文在cnki的局限性就体现出来了,我就开始培养自己的文献检索能力.现在的各种开发工具,各种论文检索网站再加上文献检索的形式越来越复杂,我们 ...
- 自己动手写把”锁”之---JMM和volatile
一.JAVA内存模型 关于Java内存模型的文章,网上真的数不胜数.在这里我就不打算说的很详细.很严谨了.只力求大家能更好的理解和运用,为后边的技术点做铺垫. 内存模型并不是Java独有的概念,而 ...
- Apache Avro# 1.8.2 Specification (Avro 1.8.2规范)一
h4 { text-indent: 0.71cm; margin-top: 0.49cm; margin-bottom: 0.51cm; direction: ltr; color: #000000; ...
- MySQL 的调节和优化的提示
MySQL 服务器硬件和操作系统调节: 1. 拥有足够的物理内存来把整个InnoDB文件加载到内存中——在内存中访问文件时的速度要比在硬盘中访问时快的多.2. 不惜一切代价避免使用Swap交换分区 – ...