c#2008网络编程socket这段代码总是错误

[复制链接]
查看11 | 回复3 | 2010-5-13 11:33:16 | 显示全部楼层 |阅读模式
public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

public string data,send;

Socket listen, handler;

private void Form1_Load(object sender, EventArgs e)

{

IPHostEntry iphostinfo = Dns.Resolve(Dns.GetHostName());

IPAddress ipaddress=iphostinfo.AddressList[0];

IPEndPoint localendpoint = new IPEndPoint(ipaddress,11000);

listen = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

try

{

listen.Bind(localendpoint);

listen.Listen(10);

textBox1.Text = "等待一个新连接......"+"\r\n";

handler = listen.Accept();

}

catch(Exception a)

{

textBox1.Text = a.ToString();

}

}

private void button1_Click(object sender, EventArgs e)

{

while(true)

{

byte[] bytes=new byte [1024];

int bytesrecieve = handler.Receive(bytes);

data += Encoding.ASCII.GetString(bytes,0,bytesrecieve);

textBox1.Text += data+"\r\n";

}

send = textBox2.Text;

byte[] msg = Encoding.ASCII.GetBytes(send);

handler.Send(msg);

}

}
}
错误代码:System.Net.Sockets.SocketException: 通常每个套接字地址(协议/网络地址/端口)只允许使用一次。
什么情况我想监听端口等待连接后,可以聊天!!!!!
这是客户端代码:
namespace socket发送接收数据
{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

byte[] bytes=new byte[1024];

Encoding ascii = Encoding.ASCII;

string recieve = string.Empty;

private void button1_Click(object sender, EventArgs e)

{

bytes = ascii.GetBytes(textBox2.Text);

IPHostEntry iphostinfo = Dns.Resolve("192.168.1.7");

IPAddress ipaddress = iphostinfo.AddressList[0];

IPEndPoint remoteip = new IPEndPoint(ipaddress,11000);

Socket sender1 = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

try

{

sender1.Connect(remoteip);

if(sender1.Connected==false)

{

textBox1.Text = "连接失败";

}

int bytessend= sender1.Send(bytes);

int bytesrecieve = sender1.Receive(bytes);

recieve += ascii.GetString(bytes,0,bytesrecieve);

textBox1.Text = recieve;

sender1.Shutdown(SocketShutdown.Both);

sender1.Close();

}

catch(Exception a)

{

textBox1.Text = a.ToString();

}

}

}
}

回复

使用道具 举报

千问 | 2010-5-13 11:33:16 | 显示全部楼层
我都忘了,不过我倒是可以提醒你一下,监听貌似是listen
回复

使用道具 举报

千问 | 2010-5-13 11:33:16 | 显示全部楼层
错误代码:System.Net.Sockets.SocketException: 通常每个套接字地址(协议/网络地址/端口)只允许使用一次。你的端口已经被其它程序用了,你用其它端口试一下吧。如果在同一部机上测试,服务器端和客户端用两个不同的端口才行。
回复

使用道具 举报

千问 | 2010-5-13 11:33:16 | 显示全部楼层
改为:IPAddress ipaddress=IPAddress.Parse("127.0.0.1")
IPEndPoint localendpoint = new IPEndPoint (ipaddress,11000); 在本机测试时改为上述代码,发布时再改回原来的代码。异步编程时我碰到过这个问题,一直没搞懂,就这样解决的。你的是同
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题

0

回帖

4882万

积分

论坛元老

Rank: 8Rank: 8

积分
48824836
热门排行