创建服务端
private void StartServer()
{
try
{
// Set the TcpListener on port 13000.
Int32 port = 8888;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// 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)
{
Debug.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also use server.AcceptSocket() here.
using TcpClient client = server.AcceptTcpClient();
Debug.WriteLine("Connected!");
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);
Debug.WriteLine("Received: {0}", data);
Dispatcher.Invoke(() =>
{
ServerReceivedTextBox.Text = data;
});
}
}
}
catch (SocketException ex)
{
Debug.WriteLine("SocketException: {0}", ex);
}
finally
{
server.Stop();
}
}
启动客户端
private void StartClient(object sender, RoutedEventArgs e)
{
if (tcpClient == null)
{
tcpClient = new TcpClient();
tcpClient.Connect(IPAddress.Loopback, 8888); //重要,用于本机测试
}
}
通过客户端向服务端发送消息
private void SendContent(object sender, RoutedEventArgs e)
{
byte[] msg = System.Text.Encoding.UTF8.GetBytes(sendingContents.Text);
if (tcpClient != null && tcpClient.Connected)
{
var stream = tcpClient.GetStream();
stream.Write(msg,0,msg.Length);
}
}
标签:tcpClient,stream,c#,本机,bytes,Tcp,server,Debug,data
From: https://www.cnblogs.com/baibaisheng/p/16932565.html