using
System;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
using
System.Windows.Forms;
using
System.Net;
using
System.Net.Sockets;
using
System.IO;
using
System.Threading;
namespace
TcpClientTest
{
public
partial
class
FormMain : Form
{
public
FormMain()
{
InitializeComponent();
}
private
void
FormMain_Load(
object
sender, EventArgs e)
{
txtSendMssg.Text =
"测试数据"
;
Thread thrListener =
new
Thread(
new
ThreadStart(Listen));
thrListener.Start();
}
private
void
FormMain_FormClosing(
object
sender, FormClosingEventArgs e)
{
Environment.Exit(0);
}
private
void
btnSend_Click(
object
sender, EventArgs e)
{
TcpClient tcpClient =
new
TcpClient();
tcpClient.Connect(IPAddress.Parse(
"127.0.0.1"
), 2014);
NetworkStream ntwStream = tcpClient.GetStream();
if
(ntwStream.CanWrite)
{
Byte[] bytSend = Encoding.UTF8.GetBytes(txtSendMssg.Text);
ntwStream.Write(bytSend, 0, bytSend.Length);
}
else
{
MessageBox.Show(
"无法写入数据流"
);
ntwStream.Close();
tcpClient.Close();
return
;
}
ntwStream.Close();
tcpClient.Close();
}
private
void
Listen()
{
Socket listener =
new
Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
listener.Bind(
new
IPEndPoint(IPAddress.Any, 2014));
while
(
true
)
{
listener.Listen(0);
Socket socket = listener.Accept();
NetworkStream ntwStream =
new
NetworkStream(socket);
StreamReader strmReader =
new
StreamReader(ntwStream);
Invoke(
new
PrintRecvMssgDelegate(PrintRecvMssg),
new
object
[] { strmReader.ReadToEnd() });
socket.Close();
}
}
private
delegate
void
PrintRecvMssgDelegate(
string
s);
private
void
PrintRecvMssg(
string
info)
{
txtRecvMssg.Text +=
string
.Format(
"[{0}]:{1}\r\n"
,
DateTime.Now.ToLongTimeString(), info);
}
}
}
请发表评论