TCP服务器+多个客户端C# [英] TCP Server + Multiple Clients C#

查看:381
本文介绍了TCP服务器+多个客户端C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我有一台TCP服务器&客户见下面的完整代码。有人可以提供示例代码或编辑我的代码,我可以如何使这个多线程请。



此外,我希望客户端从服务器接收消息,而不是将消息发送到服务器。

如果有人可以帮我,那也非常感谢。



Matt



SERVER

Hi Guys,

i have a TCP Server & Client see below for complete code. Can someone please provide sample code or edit my code on how i could make this Multithreaded please.

Also, i want the client to receive a message from the server, instead of sending the message to the server.
if someone could help me with that also it would be greatly appreciated.

Matt

SERVER

public static void Main (string[] args)
{
try {
	while (true) {
			IPAddress ipAd = IPAddress.Parse ("127.0.0.1");
			TcpListener myList = new TcpListener (ipAd, 8001);
			myList.Start ();
			Console.WriteLine ("The server is running at port 8001...");    
			Console.WriteLine ("The local End point is  :" +
			myList.LocalEndpoint);
			Console.WriteLine ("Waiting for a connection.....");
			Socket s = myList.AcceptSocket ();
			Console.WriteLine ("Connection accepted from " + s.RemoteEndPoint);
			byte[] b = new byte[100];
			int k = s.Receive (b);
			Console.WriteLine ("Recieved...");
			string Command = string.Empty;
			for (int i = 0; i < k; i++) {
				Command = Command + Convert.ToChar (b [i]);
			}
			Console.WriteLine (Command);
			ASCIIEncoding asen = new ASCIIEncoding ();
			s.Send (asen.GetBytes ("The string was recieved by the server."));
			Console.WriteLine ("\nSent Acknowledgement");        
			s.Close ();
			myList.Stop ();
		}
	} catch (Exception e) {
		Console.WriteLine ("Error..... " + e.StackTrace);
	}    
}





客户





CLIENT

try {
				while(true)
				{
				TcpClient tcpclnt = new TcpClient();
				Console.WriteLine("Connecting.....");

				tcpclnt.Connect("127.0.0.1",8001);
				// use the ipaddress as in the server program

				Console.WriteLine("Connected");
				Console.Write("Enter the string to be transmitted : ");

				String str=Console.ReadLine();
				Stream stm = tcpclnt.GetStream();

				ASCIIEncoding asen= new ASCIIEncoding();
				byte[] ba=asen.GetBytes(str);
				Console.WriteLine("Transmitting.....");

				stm.Write(ba,0,ba.Length);

				byte[] bb=new byte[100];
				int k=stm.Read(bb,0,100);

				for (int i=0;i<k;i++)
					Console.Write(Convert.ToChar(bb[i]));

				tcpclnt.Close();
				}
			}

			catch (Exception e) {
				Console.WriteLine("Error..... " + e.StackTrace);
			}

推荐答案

你离我不远!



以下是一些事情:



我会替换它:

You're not far off!

Here's a few things:

I'd replace this:
IPAddress ipAd = IPAddress.Parse ("127.0.0.1");
TcpListener myList = new TcpListener (ipAd, 8001);



with this:


with this:

TcpListener myList = new TcpListener (IPAddress.Any, 8001);



原因是127.0.0.1只适用于您的计算机而不是来自其他计算机的传入连接。



在服务器上,您接受套接字,但在客户端上接受TcpClient。两侧使用相同(TcpClient)。建立连接后,两端的工作方式完全相同。使用 AcceptTcpClient 而不是 AcceptSocket



阅读时和写入/从流写入,您需要将读/写调用放在循环中。并非所有数据都可以在一次调用中得到保证,因为它会被集中在线路上的数据包中。如果您尝试读取8k数据但读取调用仅返回5000字节,则需要再次调用以收集其余数据。



至于原始问题你需要确定连接是简短事务(线程池)还是长时间事务(新线程)。无论哪种方式,将Accept放入循环中,并将提供的TcpClient作为参数传递给threadstart。如果这没有意义,请告诉我,我会进一步解释。


Reason being that 127.0.0.1 will only work on your computer and not incoming connections from other computers.

On the server you are accepting a socket, but on the client a TcpClient. Use the same (TcpClient) on both sides. Once the connection is established both ends work exactly the same way then. Use AcceptTcpClient instead of AcceptSocket.

When reading and writing to/from the stream, you need to put the read/write calls in a loop. Not all the data can be guaranteed in a single call as it gets lumped in packets on the wire. If you try to read 8k of data but the read call only returns 5000 bytes, you need to call it again to collect the rest.

As for the original question you need to determine if connections are going to be brief affairs (threadpool) or long-running things (new thread). Either way, put the Accept in a loop, and pass the supplied TcpClient as the parameter to the threadstart. If that doesn't make sense, let me know and I'll explain further.


不完全是你问题的直接答案,但我经常给编写套接字代码的人一些建议: -



不要。



花一点时间学习ZeroMQ [ ^ ]。它是全面的,易于使用,防弹,多平台,多线程,以及你可能想要的任何其他东西。



编写套接字代码看似简单。执行效果不佳的单线程代码是轻而易举的。防弹多线程实现*不容易,有等待你的问题。



帮自己一个忙,并使用ZeroMQ ......
Not exactly a direct answer to your question, but some advice I often give to people writing socket code:-

Don't.

Spend a little time learning ZeroMQ[^]. It's comprehensive, easy to use, bulletproof, multiplatform, multithreaded, and pretty much anything else you could want.

Writing socket code is deceptively easy. Single-threaded code that performs poorly is a doddle. Bulletproof multithreaded implementations are *not* easy, there are gotchas awaiting you.

Do yourself a favour and use ZeroMQ...


这篇关于TCP服务器+多个客户端C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆