今天学习了多线程和TCP网络连接,仿佛打开了一扇新的大门,很兴奋。
贴出部分代码。
多线程:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace MultithreadingApplication
{
class ThreadCreationProgram
{
public static void CallToChildThread()
{
Thread.Sleep(10000);
Console.WriteLine("Child thread starts");
}
static void Main(string[] args)
{
Console.WriteLine("In Main: Creating the Child thread");
ThreadStart childref = new ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.WriteLine("In Main: Creating the Child thread");
Console.ReadKey();
}
}
}
TCP网络连接:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Threading;
using System.Net;
namespace ConnectTCP
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Socket newclient;
public bool Connected;
public Thread myThread;
public delegate void MyInvoke(string str);
public void Connect()
{
byte[] data = new byte[1024];
string ipadd = serverIP.Text.Trim();//将服务器IP地址存放在字符串 ipadd中
int port = Convert.ToInt32(serverPort.Text.Trim());//将端口号强制为32位整型,存放在port中
//创建一个套接字
IPEndPoint ie = new IPEndPoint(IPAddress.Parse(ipadd), port);
newclient = new Socket(IPAddress.Parse(ipadd).AddressFamily, SocketType.Stream, ProtocolType.Tcp);
textBox1.Text = Convert.ToString(IPAddress.Parse(ipadd));
textBox2.Text = Convert.ToString(ie);
//将套接字与远程服务器地址相连
try
{
newclient.Connect(ie);
button1.Enabled = false;//使连接按钮变成虚的,无法点击
Connected = true;
}
catch (SocketException e)
{
MessageBox.Show("连接服务器失败 " + e.Message);
return;
}
ThreadStart myThreaddelegate = new ThreadStart(ReceiveMsg);
myThread = new Thread(myThreaddelegate);
myThread.Start();
}
public void ReceiveMsg()
{
while (true)
{
byte[] data = new byte[1024];
newclient.Receive(data);
int length = data[5];
Byte[] datashow = new byte[length + 6];
for (int i = 0; i <= length + 5; i++)
datashow[i] = data[i];
string stringdata = BitConverter.ToString(datashow);//把数组转换成16进制字符串
//if (data[7] == 0x01) { showMsg01(stringdata + "\r\n"); };
//if (data[7] == 0x02) { showMsg02(stringdata + "\r\n"); };
//if (data[7] == 0x03) { showMsg03(stringdata + "\r\n"); };
//if (data[7] == 0x05) { showMsg05(stringdata + "\r\n"); };
//if (data[7] == 0x06) { showMsg06(stringdata + "\r\n"); };
//if (data[7] == 0x0F) { showMsg0F(stringdata + "\r\n"); };
//if (data[7] == 0x10) { showMsg10(stringdata + "\r\n"); };
}
}
private void button1_Click(object sender, EventArgs e)
{
Connect();
}
private void Form1_Load(object sender, EventArgs e)
{
serverIP.Text = "192.168.20.3";
serverPort.Text = "502";
}
}
}
代码是从别处得来,自己做了些修改,有些乱,毕竟刚开始学习还没有了解透彻。后面继续学习使用。