WPF聊天应用程序帮助C#
我需要一些关于使用套接字的WPF聊天应用程序的帮助。问题是它似乎不起作用,所以请有人告诉我我做错了什么。下面,您将在代码WPF code behind中找到我的代码:WPF聊天应用程序帮助C#,c#,wpf,windows,sockets,chat,C#,Wpf,Windows,Sockets,Chat,我需要一些关于使用套接字的WPF聊天应用程序的帮助。问题是它似乎不起作用,所以请有人告诉我我做错了什么。下面,您将在代码WPF code behind中找到我的代码: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Control
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Net.Sockets;
using System.Windows.Threading;
namespace CSSChat
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public Socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
public MainWindow()
{
InitializeComponent();
sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
textLocalIp.Text = GetLocalIP();
textRemoteIp.Text = GetLocalIP();
}
//return own IP
private string GetLocalIP()
{
string ipaddr = null;
IPHostEntry host;
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
ipaddr = ip.ToString();
return ipaddr;
}
}
//in case we didn't get it
if (ipaddr == null) throw new ArgumentNullException("IP can not be null in GetLocalIP() ");
return "127.0.0.1";
}
private void MessageCallBack(IAsyncResult ar)
{
try
{
EndPoint epRemote = new IPEndPoint(IPAddress.Parse(textRemoteIp.Text), Convert.ToInt32(textRemotePort.Text));
int size = sck.EndReceiveFrom(ar, ref epRemote);
//check if we got something
byte[] recvdata = new byte[1464];
recvdata = (byte[])ar.AsyncState;
//convert to human-readable
ASCIIEncoding enc = new ASCIIEncoding();
string recv_message = enc.GetString(recvdata);
//adding message to the listbox
this.Dispatcher.Invoke((Action)(() =>
{
listMessages.Text += "Remote box: " + recv_message;
listMessages.Text += "\r\n";
}));
//start listening again
byte[] buf = new byte[1500];
sck.BeginReceiveFrom(buf, 0, buf.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buf);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnStart_Click_1(object sender, RoutedEventArgs e)
{
{
//bind socket
try
{
this.Dispatcher.Invoke((Action)(() =>
{
EndPoint eplocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text), Convert.ToInt32(textLocalPort.Text));
sck.Bind(eplocal);
//connect to remote IP & Port
EndPoint epRemote = new IPEndPoint(IPAddress.Parse(textRemoteIp.Text), Convert.ToInt32(textRemotePort.Text));
sck.Connect(epRemote);
//start listening
byte[] buf = new byte[1500];
sck.BeginReceiveFrom(buf, 0, buf.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buf);
//send
btnStart.Content = "Connected";
btnStart.IsEnabled = false;
textMessage.Focus();
}));
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
private void btnSend_Click_1(object sender, RoutedEventArgs e)
{
try
{
this.Dispatcher.Invoke((Action)(() =>
{
//convert to human-readable
ASCIIEncoding enc = new ASCIIEncoding();
byte[] buf = new byte[1500];
buf = enc.GetBytes(textMessage.Text);
//send message
sck.Send(buf);
//add to chat window
listMessages.Text += "Me: " + textMessage.Text;
listMessages.Text += "\r\n";
//clear
textMessage.Clear();
}));
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
this.Dispatcher.Invoke(new Action(() =>
{
... your code here ...
}));
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用System.Threading.Tasks;
使用System.Windows;
使用System.Windows.Controls;
使用System.Windows.Data;
使用System.Windows.Documents;
使用System.Windows.Input;
使用System.Windows.Media;
使用System.Windows.Media.Imaging;
使用System.Windows.Navigation;
使用System.Windows.Shapes;
Net系统;
使用System.Net.Sockets;
使用System.Windows.Threading;
名称空间CSSChat
{
///
///MainWindow.xaml的交互逻辑
///
公共部分类主窗口:窗口
{
公共套接字sck=新套接字(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
公共主窗口()
{
初始化组件();
sck.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress,true);
Text=GetLocalIP();
textRemoteIp.Text=GetLocalIP();
}
//返回自己的IP
私有字符串GetLocalIP()
{
字符串ipaddr=null;
IPHostEntry宿主;
host=Dns.GetHostEntry(Dns.GetHostName());
foreach(主机地址列表中的ip地址)
{
if(ip.AddressFamily==AddressFamily.InterNetwork)
{
ipaddr=ip.ToString();
返回IPADR;
}
}
//以防我们没拿到
if(ipaddr==null)抛出新ArgumentNullException(“GetLocalIP()中的IP不能为null”);
返回“127.0.0.1”;
}
私有void MessageCallBack(IAsyncResult ar)
{
尝试
{
EndPoint epRemote=new-IPEndPoint(IPAddress.Parse(textmoteip.Text),Convert.ToInt32(textmoteport.Text));
int size=sck.EndReceiveFrom(ar,ref-epRemote);
//看看有没有什么
字节[]recvdata=新字节[1464];
recvdata=(字节[])ar.AsyncState;
//转换为人类可读的
ascienceoding enc=新的ascienceoding();
string recv_message=enc.GetString(recvdata);
//向列表框添加消息
this.Dispatcher.Invoke((操作)(()=>
{
Text+=“远程框:”+recv_消息;
listMessages.Text+=“\r\n”;
}));
//重新开始听
字节[]buf=新字节[1500];
sck.BeginReceiveFrom(buf,0,buf.Length,SocketFlags.None,ref-epRemote,new-AsyncCallback(MessageCallBack),buf);
}
捕获(例外情况除外)
{
MessageBox.Show(例如Message);
}
}
私有void btnStart\u Click\u 1(对象发送方,路由目标)
{
{
//绑定套接字
尝试
{
this.Dispatcher.Invoke((操作)(()=>
{
EndPoint eplocal=new IPEndPoint(IPAddress.Parse(textloclip.Text),Convert.ToInt32(textLocalPort.Text));
sck.Bind(eplocal);
//连接到远程IP端口(&P)
EndPoint epRemote=new-IPEndPoint(IPAddress.Parse(textmoteip.Text),Convert.ToInt32(textmoteport.Text));
sck.Connect(epRemote);
//开始听
字节[]buf=新字节[1500];
sck.BeginReceiveFrom(buf,0,buf.Length,SocketFlags.None,ref-epRemote,new-AsyncCallback(MessageCallBack),buf);
//发送
btnStart.Content=“已连接”;
btnStart.IsEnabled=false;
textMessage.Focus();
}));
}
捕获(例外情况除外)
{
Show(例如ToString());
}
}
}
私有无效BTN发送\单击\ 1(对象发送者,路由目标e)
{
尝试
{
this.Dispatcher.Invoke((操作)(()=>
{
//转换为人类可读的
ascienceoding enc=新的ascienceoding();
字节[]buf=新字节[1500];
buf=enc.GetBytes(textMessage.Text);
//发送消息
sck.发送(buf);
//添加到聊天窗口
listmessage.Text+=“我:”+textMessage.Text;
listMessages.Text+=“\r\n”;
//清楚的
textMessage.Clear();
}));
}
捕获(例外情况除外)
{
Show(例如ToString());
}
}
}
}
任何反馈都将不胜感激,谢谢 解决方案是使用一个调用程序,并将所有事件放入
this.Dispatcher.Invoke(new Action(() =>
{
... your code here ...
}));
或
this.Dispatcher.Invoke(new Action(() =>
{
... your code here ...
}));
在上面的代码中,两者都可以这样做 您是否收到任何错误?你能把代码的范围缩小到有问题的部分吗?嗨,应用程序编译顺利,没有任何错误。我在这里迷路了,一切似乎都很顺利,但当我在本地计算机或两台不同的笔记本电脑上使用两个实例进行测试时,它不会在远程计算机上发送或接收消息。两台计算机都在同一子网中?嗨,是的。我尝试使用本地IP和远程IP重定向路由器上的相应端口。路由器上的端口重定向仅适用于内存可用的外部流量。在内部子网中,您的路由器不会为r而烦恼
this.Dispatcher.Invoke(new Action(() =>
{
... your code here ...
}));