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();
}
}
}
}
|