C# TCP 服务器帮助
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace PDMS_TCG
{
public partial class FormHost : Form
{
public FormHost()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
{
IPAddress ipAd = IPAddress.Parse(txtAddress.Text);
TcpListener myList = new TcpListener(ipAd, int.Parse(txtPort.Text));
myList.Start();
Socket s = myList.AcceptSocket();
RPS rps = new RPS();
rps.Show();
}
}
private void btnHost_Click(object sender, EventArgs e)
{
IPAddress ipAd = IPAddress.Parse(GV.strAddress);
TcpListener myList = new TcpListener(ipAd, int.Parse(txtPort.Text));
myList.Start();
Socket s = myList.AcceptSocket();
}
}
}
txtAddress = 主机的 IP 地址
txtPort = 端口号
我对 TcpListener/Sockets 有一些困惑。有人可以帮我修复这个代码吗?单击 btnHost 让您托管连接,btnConnect 将连接到主机。另外,连接后,如何让 1 个事件触发另一台计算机上的事件?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
TcpClient
在客户端启动与服务器的连接 (连接
)。使用
TcpListener
在服务器端接受传入连接 (AcceptTcpClient
)。AcceptTcpClient
返回TcpClien
t。然后调用
GetStream
在两个TcpClient
上获取Stream
,您可以使用它与另一端通信(同步或异步)。TcpClient
和TcpListener
在 MSDN 中都有大量示例。看看它们,很快就会有东西运行起来。Use a
TcpClient
on the client-side to initiate a connection to the server (Connect
).Use a
TcpListener
on the server-side to accept incoming connections (AcceptTcpClient
).AcceptTcpClient
returns aTcpClien
t.Then call
GetStream
on the twoTcpClient
s to get aStream
that you can use to communicate with the other side (synchronously or asynchronously).Both
TcpClient
andTcpListener
have extensive examples in the MSDN. Have a look at them and you'll have something running pretty soon.