首页  编辑  

阻塞模式的TCP发送和接收并断开的代码

Tags: /C#/Web网络编成/   Date Created:
C# TCP/IP send raw string to remote IP/port and get response synchronize mode
		/// <summary>
		/// 向指定端口发送数据并返回读取到的数据,以回车换行结束
		/// </summary>
		/// <param name="IP"></param>
		/// <param name="port"></param>
		/// <param name="data"></param>
		/// <returns></returns>
		public static string TcpSend(string IP, int port, string data)
		{
			string ret = null;
			try
			{
				TcpClient client = new TcpClient();
				if (!client.ConnectAsync(IP, port).Wait(2000)) return null;
				client.SendTimeout = 1000;
				Stream stream = client.GetStream();
				stream.ReadTimeout = 6000;
				Byte[] bytes = System.Text.Encoding.ASCII.GetBytes(data);
				stream.Write(bytes, 0, bytes.Length);
				if (client.ReceiveBufferSize > 0)
				{
					bytes = new byte[client.ReceiveBufferSize];
					int r = stream.Read(bytes, 0, client.ReceiveBufferSize);
					ret = Encoding.ASCII.GetString(bytes, 0, r);
				}
				//StreamReader sr = new StreamReader(stream);
				//ret = sr.ReadLine();
				stream.Close();
				client.Close();
			}
			catch (Exception)
			{
				return null;
			}
			return ret;
		}