110,536
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace sock_user
{
public partial class Form1 : Form
{
private IPAddress myIP = IPAddress.Parse("172.16.5.25");
private IPEndPoint MyServer;
private Socket connectsock;
private bool check = true;
private System.ComponentModel.Container components = null;
public Form1()
{
InitializeComponent();
this.btn_connection.Click += new System.EventHandler(this.btn_connection_Click);
this.btn_send.Click += new System.EventHandler(this.btn_send_Click);
this.btn_close.Click+=new EventHandler(this.btn_close_Click);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btn_connection_Click(object sender, EventArgs e)
{
try
{
myIP = IPAddress.Parse(txt_system.Text);
}
catch
{
MessageBox.Show("对不起,你输入的IP地址不正确");
}
try
{
MyServer = new IPEndPoint(myIP, Int32.Parse(txt_ask.Text));
connectsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
connectsock.Connect(MyServer);
Thread thread = new Thread(new ThreadStart(receive));
thread.Start();
}
catch(Exception ee)
{
MessageBox.Show(ee.Message);
}
}
private void btn_send_Click(object sender, EventArgs e)
{
try
{
Byte[] sendbyte = new Byte[64];
string send = richTextBox2.Text + "\r\n";
NetworkStream netstream = new NetworkStream(connectsock);
sendbyte = System.Text.Encoding.BigEndianUnicode.GetBytes(send.ToArray());
netstream.Write(sendbyte, 0, sendbyte.Length);
netstream.Flush();
}
catch
{
MessageBox.Show("连接没有建立!无法发送");
}
}
private void btn_close_Click(object sender, EventArgs e)
{
try
{
connectsock.Close();
}
catch
{
MessageBox.Show("连接没有建立!断开无效!");
}
}
private void receive()
{
while(true)
{
Byte[] Rec = new Byte[64];
NetworkStream netstream = new NetworkStream(connectsock);
netstream.Read(Rec,0,Rec.Length);
string RecMessage=System.Text.Encoding.BigEndianUnicode.GetString(Rec);
richTextBox1.AppendText(RecMessage+"\r\n");
}
}
}
}