0

如果我運行服務器應用程序。發生異常:上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()); } } } }

回答

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

+0

我該如何重新排列我的代碼? – Penguen 2010-05-08 19:18:46

+0

@Phsika,你看了一下我鏈接到的頁面上的樣本嗎?該示例爲構建代碼提供了一個合理的起點。 – 2010-05-08 20:08:39

相關問題