如果我运行Server App。发生异常:在Dinle.Start()
上
System.Net.SocketException - 通常只允许使用每个套接字地址(协议/网络地址/端口)
我该如何解决这个错误?
alt text http://i40.tinypic.com/1g2khu.jpg Server.cs
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.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Server
{
public partial class Server : Form
{
Thread kanal;
public Server()
{
InitializeComponent();
try
{
kanal = new Thread(new ThreadStart(Dinle));
kanal.Start();
kanal.Priority = ThreadPriority.Normal;
this.Text = "Kanla Çalıştı";
}
catch (Exception ex)
{
this.Text = "kanal çalışmadı";
MessageBox.Show("hata:" + ex.ToString());
kanal.Abort();
throw;
}
}
private void Server_Load(object sender, EventArgs e)
{
Dinle();
}
private void btn_Listen_Click(object sender, EventArgs e)
{
Dinle();
}
void Dinle()
{
// IPAddress localAddr = IPAddress.Parse("localhost");
// TcpListener server = new TcpListener(port);
// server = new TcpListener(localAddr, port);
//TcpListener Dinle = new TcpListener(localAddr,51124);
TcpListener Dinle = new TcpListener(51124);
try
{
while (true)
{
Dinle.Start();
Exception is occured.
Socket Baglanti = Dinle.AcceptSocket();
if (!Baglanti.Connected)
{
MessageBox.Show("Baglanti Yok");
}
else
{
TcpClient tcpClient = Dinle.AcceptTcpClient();
if (tcpClient.ReceiveBufferSize > 0)
{
byte[] Dizi = new byte[250000];
Baglanti.Receive(Dizi, Dizi.Length, 0);
string Yol;
saveFileDialog1.Title = "Dosyayi kaydet";
saveFileDialog1.ShowDialog();
Yol = saveFileDialog1.FileName;
FileStream Dosya = new FileStream(Yol, FileMode.Create);
Dosya.Write(Dizi, 0, Dizi.Length - 20);
Dosya.Close();
listBox1.Items.Add("dosya indirildi");
listBox1.Items.Add("Dosya Boyutu=" + Dizi.Length.ToString());
listBox1.Items.Add("İndirilme Tarihi=" + DateTime.Now);
listBox1.Items.Add("--------------------------------");
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("hata:" + ex.ToString());
}
}
}
}
答案 0 :(得分:1)
多次调用TcpListener.Start。
1-在服务器构造函数中启动线程时调用
2-通过Server_Load事件处理程序中的Dinle调用
3-再次单击btn_Listen_Click事件处理程序中的按钮
我并不认为你已经完全掌握了你想要做的事情,但我认为这可以简化。
首先,您应该创建并启动一次侦听器,让我们说代码何时开始运行。之后,您可以进入一个调用AcceptTcpClient以接受连接并处理通信的循环。
您似乎也在混合Socket和TcpClient,这是不需要的。请查看以下内容,例如使用TcpListener和TcpClient的基本示例。
http://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.aspx