服务端:

代码:

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

  1. TCP发消息续传文件

    1.自定义固定协议头部.格式:([head][body][filestream]) /// <summary> /// 数据包头部 /// </summary> [Struct ...

  2. ActiveMQ发消息和收消息

    来自:http://blog.163.com/chengwei_1104/blog/static/53645274201382315625329/ ActiveMQ 是Apache出品,最流行的,能力 ...

  3. WinForm TCP异步连接之服务器端

    C# — WinForm TCP连接之服务器端 TCP连接之服务器端,涉及到如下三个函数,分别是: /***************************** ** 函数功能: 服务端监听 ** 输 ...

  4. 我们使用 Kafka 生产者在发消息的时候我们关注什么(Python 客户端 1.01 broker)

    之前使用 Kafka 的客户端消费者比较多一点,而且也是无脑订阅使用也没有深入了解过具体的参数.总的来说使用不够细节. 这次公司项目活动期间暴露非常多的问题,于是有了这篇文章. 首先我们来拆解一下 K ...

  5. java Socket通信,客户端与服务端相互发消息

    1.通信过程 网络分为应用层,http.ssh.telnet就是属于这一类,建立在传输层的基础上.其实就是定义了各自的编码解码格式,分层如下: 2.Socket连接 上述通信都要先在传输层有建立连接的 ...

  6. Learn day8 re正则表达式\search函数\反射\tcp发送消息(循环)\udp发送消息

    1.匹配单个字符 # ### 正则表达式 - 单个字符匹配 import re ''' findall 把匹配的结果直接返回到列表中 lst = re.findall("正则表达式" ...

  7. 初识python:scoket 单用户互发消息

    实现功能: 启动"服务器".通过"客户端1"连接"服务器",然后互发消息.在此过程中,有"客户端2"连接到"服 ...

  8. C#给其他程序发消息

    1.相关声明函数,SendMessage可定义两种格式. [DllImport("User32.DLL", CharSet = CharSet.Auto)]public stati ...

  9. iPad版微信终于来临了 微信5.4版搜索更智能 转账就是发消息

    等待甚久的iPad版微信终于来临了!昨日微信iOS版本更新至5.4.0.16,新增功能包括搜索公众号.识别图中二维码.面对面收钱,同时适配iPad.(微信5.4安卓版重回ios风格 导航菜单都放底栏位 ...

随机推荐

  1. Java学习的第二十二天

    1.异常处理 try...catch...finally... finally带return finally也可省略 try里面可以有try 多个异常用IllegalAgruementExceptio ...

  2. Java 解决Enum.valueOf找不到枚举出现的异常

    由于Enum.valueOf匹配不到枚举时会出现异常,这个可以用try...catch来解决,但是这样会导致代码往臃肿的道路上越走越远. 本文与其说是解决Enum.valueOf找不到枚举出现的异常还 ...

  3. C++在C的基础上改进了哪些细节

    C++ 是在C语言的基础上改进的,C语言的很多语法在 C++ 中依然广泛使用,例如:  C++ 仍然使用 char.short.int.long.float.double 等基本数据类型:   ...

  4. 天啦撸!打印日志竟然只晓得 Log4j?

    空了的时候,我都会在群里偷偷摸摸地潜水,对小伙伴们的一举一动.一言一行筛查诊断.一副班主任的即时感,让我感到非常的快乐,略微夹带一丝丝的枯燥. 这不,我在战国时代读者群里发现了这么一串聊天记录: 竟然 ...

  5. Group指定的方式如下: @Test(groups = {"fast", "unit", "database" })

    Group指定的方式如下: @Test(groups = {"fast", "unit", "database" }) public voi ...

  6. 直播软件开发之Java音视频解决方案:音视频基础知识

    概念 从信息论的观点来看,描述信源的数据是信息和数据冗余之和,即:数据=信息+数据冗余.音频信号在时域和频域上具有相关性,也即存在数据冗余.将音频作为一个信源,音频编码的实质是减少音频中的冗余. 拟信 ...

  7. Linux C 获取本机所有网卡的 IP,Mask

    0 运行环境 本机系统:Windows 10 虚拟机软件:Oracle VM VirtualBox 6 虚拟机系统:Ubuntu 18 1 代码 #include <sys/ioctl.h> ...

  8. CentOS 8.x 下尝试安装.Net 5 的运行时

    1.背景 看着不管是群里还是公众号里这几天最热闹就是.Net 5.0 正式版的发布.C#9. 当然要开发.net 5.0 的项目就需要把VisualStudio升级的v16.8.0版本了.升级后自带着 ...

  9. MSSQL 高并发下生成连续不重复的订单号

    参考: https://www.cnblogs.com/h-change/p/6699683.html 这里在数据库层面生成的,经测试确实不会重复. 附上自己修改后的版本,这里也可以预先生成一年的记录 ...

  10. 用 Cloud Performance Test怎么录制测试脚本

    Cloud Performance Test 云压力测试平台(以下简称:CPT)可以提供一站式全链路云压力测试服务,通过分布式压力负载机,快速搭建系统高并发运行场景,按需模拟千万级用户实时访问,并结合 ...