基础服务开发实例

来源:互联网 发布:8月份上海房产成交数据 编辑:程序博客网 时间:2024/04/30 23:40

代码如下

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;

namespace 基础服务开发实例
{
public partial class Form1 : Form
{
private IPAddress myIP = IPAddress.Parse("127.0.0.1");
private IPEndPoint MyServer;
private Socket sock;
private bool check = true;
private Socket accSock;
public Form1()
{
InitializeComponent();
}
//监听
private void button1_Click(object sender, EventArgs e)
{
try
{
myIP = IPAddress.Parse(textBox1.Text);
}
catch
{
MessageBox.Show("你输入的IP地址格式不正确!");
}
try
{
Thread thread = new Thread(new ThreadStart(accp));
thread.Start();
}
catch(Exception ee)
{
textBox3.AppendText(ee.Message);
}
}
//线程同步
private void accp()
{
MyServer = new IPEndPoint(myIP,Int32.Parse(textBox2.Text));
sock = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
sock.Bind(MyServer);
sock.Listen(50);
textBox3.AppendText("主机"+textBox1.Text+"端口"+textBox2.Text+"开始监听......\r\n");
accSock = sock.Accept();
if (accSock.Connected)
{
textBox3.AppendText("与客户建立连接.");
}

while (check)
{
Byte[] Rec =new Byte[64];
NetworkStream netStream = new NetworkStream(accSock);
netStream.Read(Rec,0,Rec.Length);
string RecMessage = Encoding.BigEndianUnicode.GetString(Rec);
richTextBox1.AppendText(RecMessage+"\r\n");
}
}
//发送信息
private void button2_Click(object sender, EventArgs e)
{
try
{
Byte[] sendByte = new Byte[64];
string send = richTextBox2.Text + "\r\n";
NetworkStream netStream = new NetworkStream(accSock);
sendByte = Encoding.BigEndianUnicode.GetBytes(send.ToCharArray());
netStream.Write(sendByte, 0, sendByte.Length);

}
catch
{
MessageBox.Show("连接尚未建立!无法发送!");
}
}
//停止监听
private void button3_Click(object sender, EventArgs e)
{
try
{
sock.Close();
textBox3.AppendText("主机" + textBox1.Text + "端口" + textBox2.Text + "监听停止!\r\n");

}
catch
{
MessageBox.Show("监听尚未开始,关闭无效!");
}
}
}
}

原创粉丝点击