winform订阅php消息,C# Winform 实现TCP发消息

服务端:

窗体

af9be10671a3d691390e555ef448206f.png

代码:

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();

}

///

/// 负责通信的socket

///

Socket socketSend;

///

/// 负责监听Socket

///

Socket socket;

///

/// 存放连接的socket

///

Dictionary dictionary = new Dictionary();

///

/// 开始监听

///

///

///

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);

}

///

/// 使用线程来接收数据

///

///

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);

}

}

}

///

/// 日志打印

///

///

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 list = new List();

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;

}

///

/// 发文件,

///

///

///

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);

}

///

/// 抖一抖

///

///

///

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);

}

///

/// 关闭前关闭socket

///

///

///

private void Form1_FormClosing(object sender, FormClosingEventArgs e)

{

try

{

socket.Shutdown(SocketShutdown.Both);

socket.Disconnect(false);

socket.Close();

}

catch

{

socket.Close();

}

}

}

}

客户端:

窗体

0585ea9237f6937edbf59bdd1bea92e5.png

代码

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 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");

}

///

/// 发消息

///

///

///

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);

}

}

}

}

运行结果:

1442b18c6afd69ebf8408591395ac84b.png

以上就是C# Winform 实现TCP发消息的详细内容,更多关于c# 实现TCP发消息的资料请关注脚本之家其它相关文章!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值