Service
创建一个Windows窗体应用
属性值:
首先我们编写启动按钮(监听):
IPAddress ip;
TcpListener listener;
private void buttonStart_Click(object sender, EventArgs e)
{
ip = IPAddress.Parse(this.textBoxIP.Text); //创建IP
listener = new TcpListener(ip,Convert.ToInt32(this.textBoxPort.Text)); //创建TCP监听对象
listener.Start();
this.textBoxInfo.Text = "服务器启动-" + DateTime.Now + "\r\n" + this.textBoxInfo.Text;
}
Client
各属性名称:
双击连接(创建与服务器端的连接):
TcpClient tcpClient;
private void buttonConnect_Click(object sender, EventArgs e)
{
tcpClient = new TcpClient();
try
{
tcpClient.Connect(this.textBoxIP.Text, Convert.ToInt32(this.textBoxPort.Text));
this.textBoxInfo.Text = "连接成功-" + DateTime.Now "\r\n" + this.textBoxInfo.Text;
}
catch(Exception ex)
{
MessageBox.Show("连接失败-" + ex.Message);
}
}
通信
Client
private void buttonSend_Click(object sender, EventArgs e)
{
string message = this.textBoxInput.Text;
this.textBoxInfo.Text = "发送“" + message + "”-" + DateTime.Now + "\r\n" + this.textBoxInfo.Text;
NetworkStream stream = tcpClient.GetStream();
byte[] byteArray = Encoding.Unicode.GetBytes(message);
stream.Write(byteArray,0,byteArray.Length); //发送字节数组
}
Service
IPAddress ip;
TcpListener listener;
TcpClient tcpClient;
private void buttonStart_Click(object sender, EventArgs e)
{
ip = IPAddress.Parse(this.textBoxIP.Text); //创建IP
listener = new TcpListener(ip,Convert.ToInt32(this.textBoxPort.Text)); //创建TCP监听对象
listener.Start();
this.textBoxInfo.Text = "服务器启动-" + DateTime.Now + "\r\n" + this.textBoxInfo.Text;
tcpClient = listener.AcceptTcpClient(); //中断 等待客户端的连接
this.textBoxInfo.Text = "有一个客户端连接成功-" + DateTime.Now + "\r\n" + this.textBoxInfo.Text;
NetworkStream stream = tcpClient.GetStream();
byte[] byteArray = new byte[1024];
int length = stream.Read(byteArray, 0, 1024); //会把流里面的字节数组 放到byteArray里面
//length其实就是客户端发送的字节数组长度
string receiveMessage = Encoding.Unicode.GetString(byteArray,0,length); this.textBoxInfo.Text = "有一个客户端连接成功-" + DateTime.Now + "\r\n" + this.textBoxInfo.Text;
this.textBoxInfo.Text = "接到的信息:"+ receiveMessage + " -" + DateTime.Now + "\r\n" + this.textBoxInfo.Text;
}