运行结果:

服务端代码

 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. constructor.prototype

    一个很好玩的小问题考大家对js的理解function alert (){}; ________________ // 填空 alert(1); 使1弹出  http://perfectionkills ...

  2. google C++编程风格指南之头文件的包括顺序

    google C++编程风格对头文件的包括顺序作出例如以下指示: (1)为了加强可读性和避免隐含依赖,应使用以下的顺序:C标准库.C++标准库.其他库的头文件.你自己project的头文件.只是这里最 ...

  3. node.js平台下,cropper.js实现图片裁剪预览并转换为base64发送至服务端。

    一 .准备工作 1.首先需要先下载cropper,常规使用npm,进入项目路径后执行以下命令: npm install cropper 2. cropper基于jquery,在此不要忘记引入jq,同时 ...

  4. 在Visual Studio 中开发Office Add-in

    作者:陈希章 发表于2017年7月13日 "Talk is cheap, show me the code",我们就用代码来说话吧.这一篇将给大家介绍如何开始Office Add- ...

  5. redis缓存的安装和配置

    ubantu16.04环境下安装 下载安装,依次执行命令; # 从官方网站下载安装包,注意,当前在哪个目录下执行命令,下载的包将在哪个目录下 $ wget http://download.redis. ...

  6. redis 报Operation against a key holding the wrong kind of value警告的解决方法

    WRONGTYPE Operation against a key holding the wrong kind of value github:https://github.com/antirez/ ...

  7. 大数据学习(6)MapReduce应用

    倒排索引 /** * * * <pre> *file1.txt: *hello ketty *hello tomcat * *file2.txt: *hello hadoop * *map ...

  8. MPSOC之3——centos环境配置及petalinux安装及使用

    ubuntu虽然能正常安装,但是build时会出现闪退情况,闪退后一切归零,没啥错误提示,改用centos来安装petalinux. 0.环境 vmware pro 14,centos 7.3 pet ...

  9. 关于Idea中右边的maven projects窗口找不到了如何调出来

    关于Idea中右边的maven  projects窗口找不到了如何调出来? 具体的idea版本我不太清楚,我用的是2016版,其他版本应该也是一样的. 首先idea自带了maven控件,不像Eclip ...

  10. APP之构架自己的webapi框架

    当我们学习到一定程度的时候,我们会想要去深入了解代码底层的东西,也更想拥有一个属于自己的框架.本文可能成为编写一个webapi框架的开端.有研究MVC框架的朋友会发现,mvc框架的路由MvcRoute ...