using System;
using System.Net;
using System.Net.Sockets;
namespace TY.Net
{
/// <summary>
/// 封装有关创建到 Internet 的 TCP 和 UDP 连接的详细信息。
/// </summary>
public class SocketsT
{
/// <summary>
/// 委托 收到信息时执行的委托
/// </summary>
/// <param name="mes"></param>
public delegate void ShowMessage(string mes);
/// <summary>
/// 事件 收到信息时执行的事件
/// </summary>
public event ShowMessage ShowMes;
/// <summary>
/// TCP侦听端口
/// </summary>
/// <param name="port">端口</param>
/// <param name="serverIP">目标IP</param>
public void tcpGetString(string serverIP, int port)
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
IPAddress localAddr = IPAddress.Parse(serverIP);
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while (true)
{
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.UTF8.GetString(bytes, 0, i);
showMess(data);
}
// Shutdown and end connection
client.Close();
}
}
catch (SocketException e)
{
showMess(string.Format("SocketException: {0}", e));
}
finally
{
// Stop listening for new clients.
server.Stop();
}
}
/// <summary>
/// 请重写ShowMes事件 详细看说明
/// </summary>
/// <param name="data">接收到的信息或错误信息</param>
private void showMess(String data)
{
if (ShowMes != null)
{
ShowMes(data);
}
}
/// <summary>
/// 发送连接
/// 支持中文
/// </summary>
/// <param name="serverIP">目标IP</param>
/// <param name="message">发送信息</param>
/// <param name="port">目标端口</param>
public static void tcpSendText(String serverIP, String message, int port)
{
TcpClient client = new TcpClient(serverIP, port);
// Translate the passed message into ASCII and store it as a Byte array.
Byte[] data = System.Text.Encoding.UTF8.GetBytes(message);
// Get a client stream for reading and writing.
// Stream stream = client.GetStream();
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
stream.Close();
client.Close();
}
}
}
// 使用的端口,请开启防火墙
// 并注意在窗体的线程处理
// 命令行下则不用