c#Socket送受信方法
4451 ワード
クライアント:
サービス:
/// <summary>
/// socket
/// </summary>
/// <param name="sendData"> byte[]</param>
/// <param name="ip"> IP</param>
/// <param name="port"> </param>
/// <returns> byte[]</returns>
public static byte[] SendBySocket(byte[] sendData, string ip, int port)
{
byte[] byteReceive = null;
try
{
IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(IPAddress.Parse(ip), port);
socket.Send(sendData);
int count, size = 512;
byte[] data = new byte[size];
MemoryStream ms = new MemoryStream();
while (0 != (count = socket.Receive(data, size, SocketFlags.None)))
ms.Write(data, 0, count);
byteReceive = ms.ToArray();
ms.Close();
// 2
//int bytes = 0;
//MemoryStream ms = new MemoryStream();
//while (true)
//{
// byte[] byteMessage = new byte[10];
// bytes = socket.Receive(byteMessage, byteMessage.Length, 0);
// if (bytes <= 0)
// break;
// ms.Write(byteMessage, 0, bytes);
//}
//byteReceive = ms.ToArray();
//ms.Close();
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
catch
{
return null;
}
return byteReceive;
}
サービス:
bool btnstatu = true; //
Socket listener;
//
private void btnStart_Click(object sender, EventArgs e)
{
CancellationTokenSource cts = new CancellationTokenSource();
Task task = new Task(() => Listen(cts.Token), cts.Token);
if (btnstatu)
{
task.Start();
statuBar.Text = " , ";
btnstatu = false;
btnStart.Text = " ";
}
else
{
if (listener != null)
{
listener.Close();
listener = null;
}
cts.Cancel();
statuBar.Text = " ";
btnstatu = true;
btnStart.Text = " ";
statuBar.Text = " ";
}
}
//
private void Listen(CancellationToken cts)
{
cts.ThrowIfCancellationRequested();
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, ServerConfig.ServerPort);
try
{
listener.Bind(iep);
listener.Listen(10);
while (true)
{
Socket accept = listener.Accept();
byte[] byteMessage = new byte[1024];
accept.Receive(byteMessage);
string recvMsg = Encoding.Default.GetString(byteMessage).Replace("\0", "");
ShowText(DateTime.Now.ToString("[HH:mm:ss]") + accept.RemoteEndPoint.ToString() + " :" + recvMsg);
string sendMsg = " ";
accept.Send(Encoding.Default.GetBytes(sendMsg));
accept.Shutdown(SocketShutdown.Both);
accept.Close();
}
}
catch
{
}
}
private void ShowText(string msg)
{
richTextBox1.SafeCall(() =>
{
richTextBox1.AppendText(msg);
richTextBox1.AppendText(System.Environment.NewLine);
});
}