110,534
社区成员
发帖
与我相关
我的任务
分享
public partial class Form1 : Form
{
private Socket client = null;
delegate void ThreadMethod(object obj);
ThreadMethod _tm = null;
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
//程序启动时便与远程进行连接
client = Connect("192.168.1.55", 9111);
try
{
if (client.Connected)
{
byte[] sends = Encoding.Default.GetBytes(this.textBox1.Text);
byte[] byteConvet = new byte[23];
byteConvet[0] = 0;
byteConvet[1] = 0x15;
for (int i = 2; i < 23; i++) {
byteConvet[i] = sends[i - 2];
}
client.Send(byteConvet);
string recvStr="";
byte[] recvBytes=new byte[1024];
int bytes=0;
while(true) {
bytes = client.Receive(recvBytes, recvBytes.Length, 0);
//将读取的字节数转换为字符串
recvStr += Encoding.UTF8.GetString(recvBytes, 2, bytes-2);
_tm = Show;
_tm(recvStr);
}
}
}
catch {
}
}
private Socket Connect(string ip, int port)
{
IPAddress ipa = IPAddress.Parse(ip);
IPEndPoint ipe = new IPEndPoint(ipa, port);
Socket sender = new Socket(
AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
sender.Connect(ipe);
}
catch
{
return null;
}
return sender;
}
private void Show(object obj)
{
if (!this.richTextBox1.InvokeRequired)
{
this.richTextBox1.Invoke(new EventHandler(ControlDelegate),
new object[] { obj, EventArgs.Empty });
}
}
private void ControlDelegate(object sender, EventArgs e)
{
this.richTextBox1.Text = sender.ToString();
}
public Form1()
{
InitializeComponent();
}
}