进程间通信
2024-01-02 15:56:47
服务器端
?客户端1
?客户端2
?注意客户端可以是多个客户端。
?对应代码
服务器端代码
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.Tasks;
using System.Windows.Forms;
namespace Services
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBox1.Text = getIpString();
}
private void button1_Click(object sender, EventArgs e)
{
Listen(textBox1.Text, int.Parse(textBox2.Text));
}
private void Listen(string ipstr,int port)
{
//throw new NotImplementedException();
Task.Run(() =>
{
Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listenSocket.Bind(new IPEndPoint(IPAddress.Parse(ipstr), port));
listenSocket.Listen(5);
logStr($"开始监测ip: {ipstr} 端口: {port}");
while (true)
{
Socket acceptSocke = listenSocket.Accept();
string receiveDate = Receive(acceptSocke, 5000);
if(receiveDate == "1")
this.WindowState = FormWindowState.Minimized;
if (receiveDate == "2")
this.WindowState = FormWindowState.Maximized;
logStr($"接收到{receiveDate}");
acceptSocke.Send(Encoding.Default.GetBytes("ok"));
if (acceptSocke.Connected)
{
acceptSocke.Shutdown(SocketShutdown.Both);
acceptSocke.Close();
}
}
});
}
public string Receive(Socket socket, int timeOut)
{
//throw new NotImplementedException();
string result = "";
socket.ReceiveTimeout = timeOut;
byte[] buffer = new byte[4096];
int length = 0;
try
{
length = socket.Receive(buffer);
if (length > 0)
{
//result = Encoding.Default.GetString(buffer, 0, length);
result = Encoding.UTF8.GetString(buffer, 0, length);
}
}
catch (Exception ex)
{
}
return result;
}
//public void logStr(string str)
//{
// richTextBox1.AppendText(DateTime.Now.ToString() + " " + str + "\r\n");
//}
#region 消息展示
private delegate void dlgShowMsg(string str);
private void logStr(string str)
{
if (richTextBox1.InvokeRequired)
{
dlgShowMsg dlg = new dlgShowMsg(logStr);
richTextBox1.Invoke(dlg, str);
}
else
{
if (richTextBox1.Lines.Length >= 1000)
richTextBox1.Clear();
richTextBox1.AppendText(DateTime.Now.ToString("yyyyMMdd HH:mm:ss:fff") + "->" + str + "\r\n");
}
}
#endregion
public string getIpString()
{
string s = string.Empty;
System.Net.IPAddress[] addressList = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList;
//for( int i = 0; i < addressList.Length; i++ ) {
// s += addressList[i].ToString();
//}
s= addressList[addressList.Length-1].ToString();
return s;
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
客户端代码:
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.Tasks;
using System.Windows.Forms;
namespace Clinet
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBox1.Text = getIpString();
}
private void button1_Click(object sender, EventArgs e)
{
string ip = textBox1.Text;
int port = int.Parse(textBox2.Text);
string news = textBox3.Text;
SendMessage(ip,port, news);
}
private void SendMessage(string ip, int port, string news)
{
//throw new NotImplementedException();
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ephost = new IPEndPoint(IPAddress.Parse(ip), port);
byte[] sendBytes = ASCIIEncoding.UTF8.GetBytes(news);
byte[] recvBytes = new byte[256];
string str = string.Empty;
try
{
s.Connect(ephost);
s.Send(sendBytes);
logStr($"向服务器发送了{news}");
int byteCount = s.Receive(recvBytes, recvBytes.Length,SocketFlags.None);
if( byteCount > 0 )
{
//str = Encoding.UTF8.GetString( recvBytes, 0, byteCount );
str = ASCIIEncoding.Default.GetString( recvBytes );
}
logStr($"从服务器接收到{str}");
//logStr($"");
}
catch
{
}
}
#region 消息展示
//private delegate void dlgShowMsg(string str);
private void logStr(string str)
{
if (richTextBox1.InvokeRequired)
{
//dlgShowMsg dlg = new dlgShowMsg(logStr);
Action<string> dlg = new Action<string>(logStr);
richTextBox1.Invoke(dlg, str);
}
else
{
if (richTextBox1.Lines.Length >= 1000)
richTextBox1.Clear();
richTextBox1.AppendText(DateTime.Now.ToString("yyyyMMdd HH:mm:ss:fff") + "->" + str + "\r\n");
}
}
#endregion
public string getIpString()
{
string s = string.Empty;
System.Net.IPAddress[] addressList = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList;
//for( int i = 0; i < addressList.Length; i++ ) {
// s += addressList[i].ToString();
//}
s = addressList[addressList.Length - 1].ToString();
return s;
}
}
}
此程序可以用于单台程序间通信,也可以用于不同电脑之间的通信。
讲解参考 关老师 链接
特此记录
anlog
2024年1月2日
文章来源:https://blog.csdn.net/anlog/article/details/135340965
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!