运行结果:

服务端代码

 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的更多相关文章

  1. [深入浅出WP8.1(Runtime)]Socket编程之UDP协议

    13.3 Socket编程之UDP协议 UDP协议和TCP协议都是Socket编程的协议,但是与TCP协议不同,UDP协议并不提供超时重传,出错重传等功能,也就是说其是不可靠的协议.UDP适用于一次只 ...

  2. iPhone socket 编程之BSD Socket篇

    iPhone socket 编程之BSD Socket篇 收藏在进行iPhone网络通讯程序的开发中,不可避免的要利用Socket套接字.iPhone提供了Socket网络编程的接口CFSocket, ...

  3. 老雷socket编程之websocket实现

    老雷socket编程之websocket实现 我们主要实现私聊和群聊两个功能,要在web端实现想微信QQ那样的即时通讯的功能,我们需要了解一下websocket.websocket是一种可以双向通讯的 ...

  4. 老雷socket编程之PHP利用socket扩展实现聊天服务

    老雷socket编程之PHP利用socket扩展实现聊天服务 socket聊天服务原理 PHP有两个socket的扩展 sockets和streamssockets socket_create(AF_ ...

  5. PHP Socket 编程之9个主要函数的使用之测试案例

    php的socket编程算是比较难以理解的东西吧,不过,我们只要理解socket几个函数之间的关系,以及它们所扮演的角色,那么理解起来应该不是很难了,在笔者看来,socket编程,其实就是建立一个网络 ...

  6. C#编程 socket编程之TcpClient,TcpListener,UdpClient

    应用程序可以通过 TCPClient.TCPListener 和 UDPClient 类使用传输控制协议 (TCP) 和用户数据文报协议 (UDP) 服务.这些协议类建立在 System.Net.So ...

  7. winform网络编程之TcpClient类,TcpListener类和UdpClient类

    TcpClient类和TcpListener类 (1)TcpClient的用途: 用于在同步阻止模式下通过网络来链接.发送和接受流数据,在此情况下,必须有侦听此连接的请求,而侦听的任务就交给TcpLi ...

  8. Python socket编程之二:【struct.pack】&【struct.unpack】

    import struct """通过 socket 的 send 和 recv 只能传输 str 格式的数据""" "" ...

  9. Linux系统编程(37)—— socket编程之UDP服务器与客户端

    典型的UDP客户端/服务器通讯过程: 编写UDP Client程序的步骤 1.初始化sockaddr_in结构的变量,并赋值.这里使用"8888"作为连接的服务程序的端口,从命令行 ...

随机推荐

  1. .Net 5分钟搞定网页实时监控

    一.为什么会用到网页实时监控 LZ最近在无锡买房了,虽然在上海工作,但是上海房价实在太高无法承受,所以选择还可以接受的无锡作为安身之地.买过房的小伙伴可能知道买房的流程,买房中间有一步很重要的就是需要 ...

  2. eclipse中JDK、struts2、Spring、Hibernate源码查看

    一般,我们导入的只有jar文件,所以看不到对于的java文件,如果需要看源码,必须下载对应开源包的源码,一般都是zip文件,比如Spring,下载spring-framework-2.0.8-with ...

  3. Java 常量池存放的是什么

    public class Test{ Integer i1 = 127 ; // 常量池本来就有,直接饮用常量池. String s1 = new String("aaaa"); ...

  4. 《C++程序设计语言(十周年纪念版)》【PDF】下载

    <C++程序设计语言(十周年纪念版)>[PDF]下载链接: https://u253469.pipipan.com/fs/253469-230382171 内容简介 <C++程序设计 ...

  5. 【java】对象变成垃圾被垃圾回收器gc收回前执行的操作:Object类的protected void finalize() throws Throwable

    package 对象被回收前执行的操作; class A{ @Override protected void finalize() throws Throwable { System.out.prin ...

  6. node.js之用ajax获取数据和ejs获取数据

    摘要:学了node之后有时候分不清前台和后台,今天用ajax和ejs来从后台获取数据,没有数据库,用json数据来进行模拟数据库:来区分前台和后台需要干什么? 一.用ejs获取数据 1.文件目录 2. ...

  7. [Maven] Missing artifact

    今天从朋友那拷过来一个maven工程,eclipse中maven配置好了,maven仓库也配置完毕,但是一直报Missing artifact,然后开网执行maven update,下载完jar后,还 ...

  8. Say Hello to ConstraintLayout

    ConstraintLayout介绍 ConstraintLayout让你可以在很平的view结构(没有多层布局嵌套)中构建一个复杂的布局结构. 有点像RelativeLayout, 所有的view都 ...

  9. 507. Perfect Number

    We define the Perfect Number is a positive integer that is equal to the sum of all its positive divi ...

  10. Python 项目实践三(Web应用程序)第二篇

    接着上节的继续学习,使用Django创建网页的过程通常分三个阶段:定义URL.编写视图和编写模板.首先,你必须定义URL模式,每个URL都被映射到特定的视图--视图函数获取并处理网页所需的数据.视图函 ...