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风格 导航菜单都放底栏位 ...
随机推荐
- Django实现文件上传功能
文件上传 关注公众号"轻松学编程"了解更多. 1.创建上传文件夹 在static文件夹下创建uploads用于存储接收上传的文件 在settings中配置,MEDIA_ROOT=o ...
- [Luogu P3119] [USACO15JAN]草鉴定Grass Cownoisseur (缩点+图上DP)
题面 传送门:https://www.luogu.org/problemnew/show/P3119 Solution 这题显然要先把缩点做了. 然后我们就可以考虑如何处理走反向边的问题. 像我这样的 ...
- C#3新增语法特性
C#3,.Net Framework 3.5 ,Visual Studio 2008, CLR 3.0 C#3.0新引进的语法基于.Net Framework 3.5.主要引进的语法:Linq,隐式类 ...
- 【SpringBoot】03.SpringBoot整合Servlet的两种方式
SpringBoot整合Servlet的两种方式: 1. 通过注解扫描完成Servlet组件注册 新建Servlet类继承HttpServlet 重写超类doGet方法 在该类使用注解@WebServ ...
- EF6 Code First 博客学习记录
学习一下ef6的用法 这个学习过程时按照微软官网的流程模拟了一下 就按照下面的顺序来写吧 1.连接数据库 自动生成数据库 2.数据库迁移 3.地理位置以及同步/异步处理(空了再补) 4.完全自动迁移 ...
- IDA-hook so层方法与java之间的映射关键
第一步 1.首先用ida打开so文件 第二步 第三步
- JVM简单入门
目录 初识JVM 双亲委派机制 沙箱安全机制 Native PC计数器 方法区 栈 堆 工具分析OOM GC算法 GC算法总结 JMM 初识JVM JVM的位置:jre中包含jvm. 双亲委派机制 双 ...
- jsp跳转不成功,服务器也不报错,登录页面点击登录没反应,代码如下,请韭菜园子的工友给予指导!
登录后.. 根本跳不到这个检查页面.. 这个登录成功页面也就无从谈起了!
- 不会吧!做了这么久开发还有不会NIO的,看看BAT大佬是怎么用的吧
前言 在将NIO之前,我们必须要了解一下Java的IO部分知识. BIO(Blocking IO) 阻塞IO,在Java中主要就是通过ServerSocket.accept()实现的. NIO(Non ...
- Java学习之Swing Gui编程
Java学习之Swing Gui编程 0x00 前言 前面的使用的Gui是基于Awt 去进行实现,但是在现实写Gui中 AWT实际运用会比较少. 0x01 Swing 概述 AWT 和Swing 区别 ...