【发布时间】:2013-07-31 05:20:55
【问题描述】:
您好,我正在使用 TCPCLient 和 TCPlitner 来传输数据,但是我收到了无法连接的错误 下面是我的代码
private void button1_Click(object sender, EventArgs e)
{
TcpClient tcpc = new TcpClient("192.168.21.46", 10);
NetworkStream nts = tcpc.GetStream();
if (nts.CanWrite)
{
Byte[] sends = System.Text.Encoding.ASCII.GetBytes(textBox1.Text.ToCharArray());
nts.Write(sends, 0, sends.Length);
nts.Flush();
}
}
private void button2_Click(object sender, EventArgs e)
{
TcpListener myListener = new TcpListener(10);
myListener.Start();
while (true)
{
//Accept a new connection
Socket mySocket = myListener.AcceptSocket();
if (mySocket.Connected)
{
//make a byte array and receive data from the client
Byte[] receive = new Byte[64];
int i = mySocket.Receive(receive, receive.Length, 0);
char[] unwanted = { ' ', ' ', ' ' };
string rece = System.Text.Encoding.ASCII.GetString(receive);
label1.Text = rece.TrimEnd(unwanted);
}
}
}
我以相同的形式添加了这两个按钮,并且提到的 IP 地址是我的系统 IP 地址。谁能告诉我为什么会发生这种情况。即使我也删除了防火墙设置。
【问题讨论】:
-
你同时按了两个按钮,不然我什么都不懂……
-
目标机器上的端口是否可以免费使用?
-
@Heather 第一个按钮点击连接套接字然后传输,第二个按钮接收数据
-
...我认为您没有打开的套接字可以连接。