有没有一种简单的入门级c#多线程例子
展开全部
这是我刚开始自学C#时写的一个控制台局域网聊天软件,用了多线程来监听和发送消息,代码很乱,希望能帮到你
//Program.cs
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
namespace ChatClient
{
class Program
{
static TCP tcp = new TCP();
static Thread t1 = new Thread(new ThreadStart(GetConnection));
static Thread t2 = new Thread(new ThreadStart(GetMsg));
static Thread t4 = new Thread(new ThreadStart(INI));
static string MyName, YourName, YourIP, IIP, OIP;
static int MyPort, YourPort;
static string RecXML;
static bool flag = false;
static void Main(string[] args)
{
MyPort = tcp.getPortal();
IIP = tcp.GetLocalIPAddress();
tcp.RecIni(IPAddress.Parse(IIP), MyPort);
// OIP = tcp.GetIPAddress();
#region Thread
/* show
Thread t1 = new Thread(new ThreadStart(TestMethod));
Thread t2 = new Thread(new ParameterizedThreadStart(TestMethod));
t1.IsBackground = true;
t2.IsBackground = true;
t1.Start();
t2.Start("hello");*/
t1.IsBackground = true;
t1.Start();
t4.IsBackground = false;
t4.Start();
#endregion
while (true)
{
while (flag)
tcp.SendMsg(IPAddress.Parse(YourIP), YourPort, Console.ReadLine());
}
}
private static void INI()
{
Console.WriteLine("您的局域网IP地址为: " + IIP);
Console.WriteLine("您的收信端口为: " + MyPort.ToString());
//Console.WriteLine("您的广域网IP地址为: " + OIP);
Console.Write("请输入您的聊天昵称: ");
MyName = Console.ReadLine();
Console.Write("请输入对方IP地址: ");
YourIP = Console.ReadLine();
Console.Write("请输入对方收信端口: ");
YourPort = Int32.Parse(Console.ReadLine());
#region XML
string xml = "";
xml += "<IIP>" + IIP + "</IIP>";
//xml += "<OIP>" + OIP + "</OIP>";
xml += "<PORT>" + MyPort.ToString() + "</PORT>";
xml += "<NAME>" + MyName + "</NAME>";
#endregion
tcp.SendMsg(IPAddress.Parse(YourIP), YourPort, xml);
}
private static void GetMsg()
{
while (true)
{
Console.WriteLine("\n" + YourName + " : " + tcp.RecMsg());
}
}
private static void GetConnection()
{
while (true)
{
RecXML = tcp.RecMsg();
if (RecXML.Contains("<IIP>") && RecXML.Contains("<NAME>") && RecXML.Contains("<PORT>"))
{
Console.Clear();
YourIP = RecXML.Substring(RecXML.IndexOf("<IIP>") + 5, RecXML.IndexOf("</IIP>") - RecXML.IndexOf("<IIP>") - 5);
YourPort = Int32.Parse(RecXML.Substring(RecXML.IndexOf("<PORT>") + 6, RecXML.IndexOf("</PORT>") - RecXML.IndexOf("<PORT>") - 6));
YourName = RecXML.Substring(RecXML.IndexOf("<NAME>") + 6, RecXML.IndexOf("</NAME>") - RecXML.IndexOf("<NAME>") - 6);
tcp.RecIni(IPAddress.Parse(IIP), MyPort);
Console.WriteLine("已连接 — " + YourName + " : " + YourIP + ":" + YourPort.ToString());
t4.Abort();
if (string.IsNullOrWhiteSpace(MyName))
{
Console.WriteLine("由于您为输入聊天昵称,您的昵称定为Unknown ");
MyName = "Unknown";
}
#region XML
string xml = "";
xml += "<IIP>" + IIP + "</IIP>";
//xml += "<OIP>" + OIP + "</OIP>";
xml += "<PORT>" + MyPort.ToString() + "</PORT>";
xml += "<NAME>" + MyName + "</NAME>";
xml += "<FINAL></FINAL>";
#endregion
if (!RecXML.Contains("<FINAL></FINAL>"))
tcp.SendMsg(IPAddress.Parse(YourIP), YourPort, xml);
t2.IsBackground = true;
t2.Start();
flag = true;
Console.WriteLine("按下回车以开始聊天");
t1.Abort();
}
}
}
private static void EnumComputers()
{
try
{
for (int i = 1; i <= 255; i++)
{
Ping myPing;
myPing = new Ping();
myPing.PingCompleted += new PingCompletedEventHandler(_myPing_PingCompleted);
string pingIP = "192.168.0." + i.ToString();
myPing.SendAsync(pingIP, 1000, null);
}
}
catch
{
}
}
private static void _myPing_PingCompleted(object sender, PingCompletedEventArgs e)
{
if (e.Reply.Status == IPStatus.Success)
{
Console.WriteLine(e.Reply.Address.ToString() + "|" + Dns.GetHostByAddress(IPAddress.Parse(e.Reply.Address.ToString())).HostName);
}
}
}
}
//TCP.cs
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace ChatClient
{
public class TCP
{
static TcpClient Rclient = null;
static TcpClient Sclient = null;
static NetworkStream stream = null;
static byte[] buffer = null;
static string receiveString = null;
static byte[] sendData = null;//要发送的字节数组
static TcpListener listener;
public void RecIni(IPAddress IP, int Port)
{
listener = new TcpListener(IP, Port);//用本地IP和端口实例化Listener
listener.Start();//开始监听
}
public string RecMsg()
{
listener.Start();
Rclient = listener.AcceptTcpClient();//接受一个Client
buffer = new byte[Rclient.ReceiveBufferSize];
stream = Rclient.GetStream();//获取网络流
stream.Read(buffer, 0, buffer.Length);//读取网络流中的数据
stream.Close();//关闭流
Rclient.Close();//关闭Client
listener.Stop();
receiveString = Encoding.Default.GetString(buffer).Trim('\0');//转换成字符串
return receiveString;
}
public void SendMsg(IPAddress remoteIP, int remotePort, string sendString)
{
sendData = Encoding.Default.GetBytes(sendString);//获取要发送的字节数组
Sclient = new TcpClient();//实例化TcpClient
try
{
Sclient.Connect(remoteIP, remotePort);//连接远程主机
}
catch (System.Exception ex)
{
Console.WriteLine("连接超时,对方可能已离线!");//连接失败
Console.ReadKey();
return;
}
stream = Sclient.GetStream();//获取网络流
stream.Write(sendData, 0, sendData.Length);//将数据写入网络流
stream.Close();//关闭网络流
Sclient.Close();//关闭客户端
}
public int getPortal()
{
Random ran = new Random();
int RandKey = ran.Next(1025, 65534);
while (true)
{
if (NotUsed(RandKey))
return RandKey;
else
RandKey = ran.Next(1025, 65534);
}
}
private bool NotUsed(int MonitorPort)
{
Socket listenSocket = null;
try
{
IPEndPoint LocalIp = new IPEndPoint(IPAddress.Any, MonitorPort);
listenSocket = new Socket(LocalIp.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listenSocket.Bind(LocalIp);
return true; // 没有被占用
}
catch
{
return false; //被占用
}
finally
{
if (listenSocket != null)
listenSocket.Close();
}
}
public string GetLocalIPAddress()
{
//获得局域网的IP地址
IPHostEntry ihe = Dns.GetHostByName(Dns.GetHostName());
IPAddress myIp = ihe.AddressList[0];
string loginIP = myIp.ToString();
return loginIP;
}
public string GetIPAddress()
{
string strUrl = "http://1212.ip138.com/ic.asp";
Uri uri = new Uri(strUrl);
WebRequest webreq = WebRequest.Create(uri);
Stream s = webreq.GetResponse().GetResponseStream();
StreamReader sr = new StreamReader(s, Encoding.Default);
string all = sr.ReadToEnd();
int i = all.IndexOf("[") + 1;
int j = all.IndexOf("]");
//分析字符串得到IP
string ip = all.Substring(i, j - i);
return ip;
#region
#endregion
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询