我正在C#中創建一個聊天客戶端在本地主機上進行演示。> 1客戶端無法連接到服務器在c#
下面是相關代碼:
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.Net.Sockets;
using System.Net;
using System.IO;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
static List<TcpListener> garabage_collection_preventor = new List<TcpListener>();
static Dictionary<IPEndPoint, bool> address_dictionary = new Dictionary<IPEndPoint, bool>();
static int port_increment = 9999;
static int client_id = 0;
void start_listening()
{
while (true)
{
TcpListener listen = new TcpListener(IPAddress.Any, port_increment);
garabage_collection_preventor.Add(listen);
listen.Start();
TcpClient client = listen.AcceptTcpClient();
IPEndPoint temp_end = ((IPEndPoint)listen.LocalEndpoint);
address_dictionary.Add(temp_end, false);
port_increment++;
new Thread(new ParameterizedThreadStart(connection_stuff)).Start(client);
}
}
void writer(object ob,int end_point)
{
StreamWriter write = ob as StreamWriter;
while (true)
{
foreach (KeyValuePair<IPEndPoint, bool> value in address_dictionary)
{
IPEndPoint index = value.Key;
int temp = value.Key.Port;
if (temp == end_point)
{
while (address_dictionary[index] == true)
{
write.WriteLine(msg_box.Text);
}
}
}
}
}
void reader(StreamReader read)
{
while (true)
{
MessageBox.Show(read.ReadLine());
}
}
void connection_stuff(object ob)
{
TcpClient client = ob as TcpClient;
int writer_identification_endpoint = ((IPEndPoint)client.Client.LocalEndPoint).Port;
NetworkStream stream = client.GetStream();
StreamReader read = new StreamReader(stream);
StreamWriter write = new StreamWriter(stream);
ThreadStart port_passing = delegate { writer(write, writer_identification_endpoint); };
Thread thread = new Thread(port_passing);
reader(read);
thread.Start();
}
public Form1()
{
InitializeComponent();
}
private void send_Click(object sender, EventArgs e)
{
int end_point = int.Parse(port.Text);
foreach (KeyValuePair<IPEndPoint, bool> value in address_dictionary)
{
IPEndPoint index = value.Key;
int temp = value.Key.Port;
if (temp == end_point)
{
address_dictionary[index] = true;
}
}
}
private void listener_Click(object sender, EventArgs e)
{
new Thread(start_listening).Start();
listener.Enabled = false;
}
}
}
現在的問題是,第一個客戶端可以方便地與程序連接,併發送該程序可以輕鬆讀取信息。但是,每個後續客戶端都無法連接。
我知道我不應該創建超過一個TCPListener,但問題是我必須演示本地主機上的程序和端口號是區分客戶端的唯一真實方法。
所以請告訴我我的頭撞牆上的代碼有什麼問題幾個小時。
編輯
這是當英語不是:)此代碼(不是目前完成)第一語言發生了什麼將是一個聊天客戶端。此代碼的每個實例都能夠與此相同代碼的其他實例進行通信。任何數量的實例都應該能夠連接任意數量的實例(例如,如果雙擊5次程序,現在將有5個實例可以彼此通信)。
現在的問題是,每個實例將具有相同的IP地址(因爲它們都運行在同一臺計算機上)。問題出現在實例1假設連接到實例4時,因爲實例2,3和5也具有相同的IP地址,所以在這裏不能使用ip。所以我想要做的是將實例1與實例4連接到IP地址和端口,而不是像使用單個TCPListener那樣只使用IP地址。
可能重複(http://stackoverflow.com/questions/13404803/tcplistener-tcpclient-stops-processing-data-under-certain-circumstances) –