运行结果:

服务端代码

 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. springMVC(1)---获取前段数据

    springMVC(1)---获取前段数据 首先说明,如果你学过Struts2,那么在学springMVC就会简单很多,我也不最基础的开始写了,我前篇文章搭建了个ssm框架,算是springmvc入门 ...

  2. 关于Oracle处理DDL和DML语句的事务管理

    SQL主要程序设计语言 数据定义语言DDL(Data Definition Language) 如 create.alter.drop, 数据操作语言DML(Data Munipulation Lan ...

  3. 【quickhybrid】API的分类:短期API、长期API

    前言 一切就绪,开始规划API,这里在规划前对API进行了一次分类:短期API.长期API 首先申明下,这个是在实际框架演变过程中自创的一个概念,其它混合框架可能也会有这个概念,但应该是会在原生底层来 ...

  4. Java中流-----个人总结心得

    流 字符流 字节流 缓冲区 数据流---用于传输数据.IO流---Input/Output流.数据从外部流向程序---输入流:数据从程序流向外部的时候--输出流.读取一个文件---数据从文件流向程序- ...

  5. 阿里云ECS部署ZooKeeper注意事项

    如果ECS为专有网络+弹性IP时,配置集群中,"自己"的ip要写成0.0.0.0,其他服务器可以写成公网ip.否则会包如下错误: java.net.BindException: C ...

  6. Asp.Net Web API(六)

    Asp.Net Web API不可以需要IIS.可以自己在主机上承载一个Web API 创建WebAPI.Server项目 创建一个控制器项目的服务端 在Nuget中添加Microsoft.AspNe ...

  7. 【CSS3】布局

    浮动布局: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <tit ...

  8. 1_3 C语言解决求n!

    求n!(n为键盘输入的任意整数值).要求分别用while语句和for语句实现 用while语句实现: #include <stdio.h> int main() { int n; scan ...

  9. vue2 vue-rout

    vue 2.0的路由比起1.0简单了许多,分为以下几个步骤: 1.创建路由块和视图块: to里面是要切换的路径名称 <div id="app"> <div> ...

  10. Maven安装教程

    一.安装Maven及配置环境变量 1.Maven官网地址:http://maven.apache.org/download.cgi  下载apache-maven-3.5.0-bin.zip文件 2. ...