这是一个简单的即时通讯服务端,关键的地方我已经标注,希望做即时通讯又无从下手的朋友可以做为学习材料! 祝好运!
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace yjyserver
{
/// <summary>
/// 及时通讯服务器。
/// </summary>
class server
{
public static Socket socket;
public static string str;
public static Thread thread;
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
IPAddress serverip=Dns.GetHostByName(Dns.GetHostName()).AddressList[0]; //获取本机IP地址
TcpListener listener=new TcpListener(serverip,8006); //监听8006端口
listener.Start();
Console.WriteLine("服务器已经启动,等待连接.....)");
while(true) //为每一个新的客户开启一个服务线程
{
socket=listener.AcceptSocket(); //接受请求
thread=new Thread(new ThreadStart(start)); //创建客户线程
thread.Start(); //开启线程
//准备下次连接;
}
}
public static void start()
{
int port=socket.RemoteEndPoint.ToString().IndexOf(":"); //获取客户句柄中的端口号
string remoteip=socket.RemoteEndPoint.ToString().Substring(0,port); //获取客户句柄中的IP
NetworkStream ns=new NetworkStream(socket); //创建网络访问的基础数据流对象
StreamReader reader=new StreamReader(ns); //创建数据流读对象
StreamWriter writer=new StreamWriter(ns); //创建数据流写对象
string receive=reader.ReadLine();
str=receive.Substring(0,5);
switch(str)
{
case "HELLO":
writer.WriteLine("OK");
writer.Flush();
break;
case "BYBYE":
string name=receive.Substring(5,receive.Length-5);
File.Delete("C:/"+name+"IP.txt");
goto Out;
default:
goto Out;
}
if(reader.ReadLine()=="HELLO")
{
writer.WriteLine("OK");
writer.WriteLine(remoteip);
writer.Flush();
}
else
goto Out;//测试连接;
str=reader.ReadLine();*/
str=reader.ReadLine();
if(File.Exists("C:/"+str+".txt"))
{
writer.WriteLine("EXISTS");
writer.Flush();
}
else
{
writer.WriteLine("NOEXISTS");
writer.Flush();
goto Out;
}//检测用户名;
string passwd=reader.ReadLine();
StreamReader file=File.OpenText("C:/"+str+".txt");
if(file.ReadLine()==passwd)
{
writer.WriteLine("CONNECTED");
writer.Flush();
FileStream f=File.OpenWrite("C:/"+str+"IP.txt");
StreamWriter write=new StreamWriter(f);
write.WriteLine(remoteip);
write.Close();
f.Close();
}
else
{
writer.WriteLine("ERROR");
writer.Flush();
file.Close();
goto Out;
}//检测密码;
string[] logged=new string[10];
int x;
for(x=0;;x++)
{
logged[x]=file.ReadLine();
if(file.Peek()!=-1)
continue;
else
break;
}
file.Close();
int con=0;
bool exit=false;
while(reader.ReadLine()=="GET")
{
for(int y=con;y<=x;y++)
{
if(File.Exists("C:/"+logged[y]+"IP.txt"))
{
writer.WriteLine(logged[y]);
writer.Flush();
reader.ReadLine();
StreamReader r=File.OpenText("C:/"+logged[y]+"IP.txt");
writer.WriteLine(r.ReadLine());
writer.Flush();
r.Close();//关闭客户文件;*/
con=y+1;
break;
}
else
{
if(y==x)
{
exit=true;
break;
}
else
{
con=y+1;
continue;
}
}
}
if(exit==true)
break;
}
writer.WriteLine("OVER");
writer.Flush();
Out:
Console.WriteLine("退出...");
}
}
}