110,567
社区成员
发帖
与我相关
我的任务
分享
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 accp()
{
try
{
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 = System.Text.Encoding.BigEndianUnicode.GetString(rec);
richTextBox1.AppendText(recMessage + "\r\n");
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
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 ex)
{
textBox3.AppendText(ex.Message);
}
}
}