C# Winform TCP发消息
服务端:

代码:
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms; namespace SocketStudy
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 负责通信的socket
/// </summary>
Socket socketSend; /// <summary>
/// 负责监听Socket
/// </summary>
Socket socket; /// <summary>
/// 存放连接的socket
/// </summary>
Dictionary<string, Socket> dictionary = new Dictionary<string, Socket>(); /// <summary>
/// 开始监听
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
//创建监听的socket,
//SocketType.Stream 流式对应tcp协议
//Dgram,数据报对应UDP协议
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//创建IP地址和端口号
IPAddress ip = IPAddress.Any;//IPAddress.Parse(textServerIP.Text);
int port = Convert.ToInt32(textServerPort.Text);
IPEndPoint iPEndPoint = new IPEndPoint(ip, port); //让负责监听的Socket绑定ip和端口号
socket.Bind(iPEndPoint); ShowLog("监听成功!" + ip + "\t" + port);//打印日志 //设置监听队列
socket.Listen(10);//一段时间内可以连接到的服务器的最大数量
Thread thread = new Thread(Listen);
thread.IsBackground = true;
thread.Start(socket);
} /// <summary>
/// 使用线程来接收数据
/// </summary>
/// <param name="o"></param>
private void Listen(object o)
{
Socket socket = o as Socket;
while(true){
//负责监听的socket是用来接收客户端连接
//创建负责通信的socket
socketSend = socket.Accept();
dictionary.Add(socketSend.RemoteEndPoint.ToString(), socketSend);
clientCombo.Items.Add(socketSend.RemoteEndPoint.ToString()); ShowLog(socketSend.RemoteEndPoint.ToString() + "已连接"); //开启新线程,接收客户端发来的信息
Thread th = new Thread(receive);
th.IsBackground = true;
th.Start(socketSend);
}
} //服务器接收客户端传来的消息
private void receive(object o)
{
Socket socketSend = o as Socket;
while (true)
{
try
{
//客户端连接成功后,服务器接收客户端发来的消息
byte[] buffer = new byte[1024 * 1024 * 2];//2M大小
//接收到的有效字节数
int length = socketSend.Receive(buffer);
if (length == 0)
{
ShowLog(socketSend.RemoteEndPoint.ToString() + "下线了。");
dictionary[socketSend.RemoteEndPoint.ToString()].Shutdown(SocketShutdown.Both);
dictionary[socketSend.RemoteEndPoint.ToString()].Disconnect(false);
dictionary[socketSend.RemoteEndPoint.ToString()].Close();
break;
}
string str = Encoding.ASCII.GetString(buffer, 0, length);
ShowLog(socketSend.RemoteEndPoint.ToString() + "\n\t" + str);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
} /// <summary>
/// 日志打印
/// </summary>
/// <param name="str"></param>
private void ShowLog(string str)
{
textLog.AppendText(str + "\r\n");
} private void Form1_Load(object sender, EventArgs e)
{
//取消对跨线程调用而产生的错误
Control.CheckForIllegalCrossThreadCalls = false;
} private void sendMsgBtn_Click(object sender, EventArgs e)
{
string txt = textMsg.Text;
byte[] buffer = Encoding.UTF8.GetBytes(txt);
List<byte> list = new List<byte>();
list.Add(0); // 0 为 发消息
list.AddRange(buffer);
byte[] newBuffer = list.ToArray();
//socketSend.Send(buffer);
string ip = clientCombo.SelectedItem.ToString();//获取选中的ip地址
Socket socketsend=dictionary[ip];
socketsend.Send(newBuffer);
} private void selectBtn_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.InitialDirectory=@"D:";
fileDialog.Title="选择文件";
fileDialog.Filter = "所有文件|*.*";
fileDialog.ShowDialog(); pathTxt.Text = fileDialog.FileName; } /// <summary>
/// 发文件,
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void sendFileBtn_Click(object sender, EventArgs e)
{
string path = pathTxt.Text;
FileStream fileStream = new FileStream(path,FileMode.Open,FileAccess.Read); byte[] buffer = new byte[1024*1024*3];
buffer[0] = 1;// 1 为发文件的标志位
int length = fileStream.Read(buffer, 1, buffer.Length-1);
fileStream.Close();
string ip = clientCombo.SelectedItem.ToString();//获取选中的ip地址
Socket socketsend = dictionary[ip];
socketsend.Send(buffer,0, length+1, SocketFlags.None);
} /// <summary>
/// 抖一抖
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void shockBtn_Click(object sender, EventArgs e)
{
byte[] buffer = new byte[1];
buffer[0] = 2;// 2 为抖一抖
string ip = clientCombo.SelectedItem.ToString();//获取选中的ip地址
Socket socketsend = dictionary[ip];
socketsend.Send(buffer);
} /// <summary>
/// 关闭前关闭socket
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
socket.Shutdown(SocketShutdown.Both);
socket.Disconnect(false);
socket.Close();
}
catch
{
socket.Close();
}
}
}
}
客户端:

代码:using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms; namespace Client
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Socket socket;
//连接
private void connectBtn_Click(object sender, EventArgs e)
{
try
{
//创建负责通信的socket
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//地址、端口
IPAddress ip = IPAddress.Parse(ipText.Text);
int serverPort = Convert.ToInt32(portText.Text);
IPEndPoint port = new IPEndPoint(ip, serverPort);
//连接到服务器
socket.Connect(port);
ShowLog("已连接"); //启动接收数据线程
Thread th = new Thread(receive);
th.IsBackground = true;
th.Start();
}
catch { }
}
//日志
private void ShowLog(string str)
{
textLog.AppendText(str + "\r\n");
} /// <summary>
/// 发消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void sendMsgBtn_Click(object sender, EventArgs e)
{
try
{
string txt = sendMsg.Text;
byte[] buffer = Encoding.ASCII.GetBytes(txt);//ascii编码
socket.Send(buffer);
}
catch { }
}
//接收消息
private void receive()
{
while (true)
{
try
{
byte[] buffer = new byte[1024 * 1024 * 2];
int length = socket.Receive(buffer);
if (length == 0)
{
break;
}
if (buffer[0] == 0)
{
string txt = Encoding.UTF8.GetString(buffer, 1, length-1);
ShowLog(socket.RemoteEndPoint + ":\r\t" + txt);
}else if (buffer[0] == 1)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = @"E:\";
saveFileDialog.Title = "饿了吃什么";
saveFileDialog.Filter = "所有文件 | *.*";
saveFileDialog.ShowDialog(this); string path = saveFileDialog.FileName;
FileStream fileStreamWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
fileStreamWrite.Write(buffer,1,length-1);
fileStreamWrite.Close();
MessageBox.Show("保存成功");
}else if (buffer[0] == 2)
{
ZD();
}
}
catch { }
}
}
//震动
private void ZD()
{
for(int i=0;i<20;i++){
if (i%2==0)
{
this.Location = new System.Drawing.Point(500, 500);
}
else
{
this.Location = new System.Drawing.Point(530, 530);
}
Thread.Sleep(20);
}
}
//取消跨线程检查
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
//关闭前关掉socket
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
socket.Disconnect(false);
socket.Close();
}
//断开连接
private void button1_Click(object sender, EventArgs e)
{
if (socket !=null)
{
socket.Disconnect(false);
}
}
}
}
结果:

C# Winform TCP发消息的更多相关文章
- TCP发消息续传文件
1.自定义固定协议头部.格式:([head][body][filestream]) /// <summary> /// 数据包头部 /// </summary> [Struct ...
- ActiveMQ发消息和收消息
来自:http://blog.163.com/chengwei_1104/blog/static/53645274201382315625329/ ActiveMQ 是Apache出品,最流行的,能力 ...
- WinForm TCP异步连接之服务器端
C# — WinForm TCP连接之服务器端 TCP连接之服务器端,涉及到如下三个函数,分别是: /***************************** ** 函数功能: 服务端监听 ** 输 ...
- 我们使用 Kafka 生产者在发消息的时候我们关注什么(Python 客户端 1.01 broker)
之前使用 Kafka 的客户端消费者比较多一点,而且也是无脑订阅使用也没有深入了解过具体的参数.总的来说使用不够细节. 这次公司项目活动期间暴露非常多的问题,于是有了这篇文章. 首先我们来拆解一下 K ...
- java Socket通信,客户端与服务端相互发消息
1.通信过程 网络分为应用层,http.ssh.telnet就是属于这一类,建立在传输层的基础上.其实就是定义了各自的编码解码格式,分层如下: 2.Socket连接 上述通信都要先在传输层有建立连接的 ...
- Learn day8 re正则表达式\search函数\反射\tcp发送消息(循环)\udp发送消息
1.匹配单个字符 # ### 正则表达式 - 单个字符匹配 import re ''' findall 把匹配的结果直接返回到列表中 lst = re.findall("正则表达式" ...
- 初识python:scoket 单用户互发消息
实现功能: 启动"服务器".通过"客户端1"连接"服务器",然后互发消息.在此过程中,有"客户端2"连接到"服 ...
- C#给其他程序发消息
1.相关声明函数,SendMessage可定义两种格式. [DllImport("User32.DLL", CharSet = CharSet.Auto)]public stati ...
- iPad版微信终于来临了 微信5.4版搜索更智能 转账就是发消息
等待甚久的iPad版微信终于来临了!昨日微信iOS版本更新至5.4.0.16,新增功能包括搜索公众号.识别图中二维码.面对面收钱,同时适配iPad.(微信5.4安卓版重回ios风格 导航菜单都放底栏位 ...
随机推荐
- Java学习的第二十天
1.类是单继承的,类是多继承的.. 接口只能继承接口 标识接口没有任何的属性和方法 2.今天没有问题 3.明天学习综合实例和第八章开头部分
- python机器学习实现线性回归
线性回归 关注公众号"轻松学编程"了解更多. [关键词]最小二乘法,线性 一.普通线性回归 1.原理 分类的目标变量是标称型数据,而回归将会对连续型的数据做出预测. 应当怎样从一大 ...
- 使用 Iceberg on Kubernetes 打造新一代云原生数据湖
背景 大数据发展至今,按照 Google 2003年发布的<The Google File System>第一篇论文算起,已走过17个年头.可惜的是 Google 当时并没有开源其技术,& ...
- 关于红黑树,在HashMap中是怎么应用的?
关于红黑树,在HashMap中是怎么应用的? 前言 在阅读HashMap源码时,会发现在HashMap中使用了红黑树,所以需要先了解什么是红黑树,以及其原理.从而再进一步阅读HashMap中的链表到红 ...
- 转载-Java匿名内部类
作者: chenssy 出处: http://www.cnblogs.com/chenssy/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接, ...
- 微服务网关Zuul和Gateway的区别
spring-cloud-Gateway是spring-cloud的一个子项目.而zuul则是netflix公司的项目,只是spring将zuul集成在spring-cloud中使用而已.因为zuul ...
- c#中简单工厂模式
运算类 public class yunsuan { public static operation create(string operate) { operation oper = null; s ...
- Grafana+Prometheus+node_exporter监控,Grafana无法显示数据的问题
环境搭建: 被测linux机器上部署了Grafana,Prometheus,node_exporter,并成功启动了它们. Grafana中已经创建了Prometheus数据源,并测试通过,并且导入了 ...
- Java读取Excel报错Unable to recognize OLE stream
Unable to recognize OLE stream 的解决方法 将xlsx用excel打开并另存为2003的xls,然后再运行即可解决问题 File file = new File(&quo ...
- ERP中HR模块的操作与设计--开源软件诞生26
赤龙ERP的EHR功能讲解--第26篇 用日志记录"开源软件"的诞生 [进入地址 点亮星星]----祈盼着一个鼓励 博主开源地址: 码云:https://gitee.com/red ...