我正在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) –