xuliehua类库
复制代码 代码如下:
using system;
using system.collections;
using system.collections.generic;
using system.threading;
using system.runtime.serialization;
using system.runtime.serialization.formatters.binary;
using system.text;
using system.io;
using system.net;
using system.net.sockets;
namespace xuliehua
{
[serializable]
public struct netmsg
{
public ipaddress fip; //发送者的ip。
public string msg; //发送的消息。
public ipaddress jieip; //接收者的ip。
public int port; //端口。
}
public class xulie
{
/// <summary>
/// 序列化
/// </summary>
/// <param ></param>
/// <returns></returns>
public static byte[] objtobyte(object obj)
{
byte[] tmp = null;
memorystream fs = new memorystream();
try
{
binaryformatter xu = new binaryformatter();
xu.serialize(fs, obj);
tmp = fs.toarray();
}
catch (exception err)
{
throw err;
}
finally
{
fs.close();
}
return tmp;
}
/// <summary>
/// 反列化
/// </summary>
/// <param ></param>
/// <returns></returns>
public static object bytetoobj(byte[] tmp)
{
memorystream fs = null;
object obj = null;
try
{
fs = new memorystream(tmp);
fs.position = 0;
binaryformatter xu = new binaryformatter();
obj = xu.deserialize(fs);
}
catch (exception err)
{
throw err;
}
finally
{
fs.close();
}
return obj;
}
}
public class serverjieshou
{
private static tcpclient client;
public thread th;
private arraylist arr;
private logtext log;
private bool tiao = true;
private timer time1;
private timercallback time;
public serverjieshou(tcpclient sclient, arraylist arr)
{
log = new logtext("连接") ;
client = sclient;
arr = arr;
th = new thread(new threadstart(thsub));
th.isbackground = true;
th.start();
time = new timercallback(xintiao);
time1 = new timer(time, null, 15000, -1);
}
private void xintiao(object state)
{
if (tiao == true)
{
tiao = false;
}
else
{
client = null;
}
}
private void thsub()
{
try
{
while (client != null)
{
networkstream net = client.getstream();
if (net.dataavailable == true) //有数据。
{
byte[] tmp = new byte[1024];
if (net.canread == true)
{
memorystream memory = new memorystream();
memory.position = 0;
int len = 1;
while (len != 0)
{
if (net.dataavailable == false) { break; }
len = net.read(tmp, 0, tmp.length);
memory.write(tmp, 0, len);
}
log.logwriter("接收完毕");
netmsg msg = (netmsg)xulie.bytetoobj(memory.toarray());
log.logwriter("序列化完毕");
tcpclient tcpclient = new tcpclient();
log.logwriter("建立tcp对象");
if (msg.fip != null) //非心跳包。
{
try
{
tcpclient.connect(msg.jieip, msg.port);
networkstream subnet = tcpclient.getstream();
byte[] tmp = xulie.objtobyte(msg);
subnet.write(tmp, 0, tmp.length);
}
catch (socketexception)
{
msg.msg = "对方不在线";
byte[] tmp = xulie.objtobyte(msg);
net.write(tmp, 0, tmp.length);
}
}
else
{
if (msg.msg == "quit")
{
arr.remove(client);
return;
}
}
tcpclient.close();
gc.collect();
}
}
else //没有数据。
{
}
thread.sleep(1000);
}
}
catch
{
arr.remove(client);
th.abort();
}
}
}
}
日志输出类
复制代码 代码如下:
using system;
using system.text;
using system.io;
using system.windows.forms;
namespace xuliehua
{
/// <summary>
/// 错误日志的输出。
/// </summary>
public class logtext
{
private string apppath;
private streamwriter strw;
private string filename;
public logtext(string filename1)
{
apppath = application.startuppath +@"\log";
try
{
if (directory.exists(apppath) == false)
{
directory.createdirectory(apppath);
}
if (file.exists(apppath+@"\"+filename+".log") == false)
{
file.create(apppath+@"\"+filename+".log");
}
filename = filename1;
}
catch{}
}
public void logwriter(string text)
{
try
{
strw = new streamwriter(apppath+@"\"+filename+".log",true);
strw.writeline("时间:{0} 描述:{1} \r\n",datetime.now.tostring(),text);
strw.flush();
strw.close();
}
catch{}
}
}
}
服务器
复制代码 代码如下:
using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.text;
using system.windows.forms;
using system.io;
using system.net;
using system.threading;
using xuliehua;
using system.net.sockets;
using system.collections;
namespace 服务器
{
public partial class frmserver : form
{
public frmserver()
{
initializecomponent();
}
private arraylist arr;
private tcplistener server1;
private tcpclient col;
private arraylist lianjie;
private void frmserver_load(object sender, eventargs e)
{
arr = new arraylist();
lianjie = new arraylist();
server1 = new tcplistener(dns.gethostaddresses(dns.gethostname())[0], 8000);
server1.start();
timer1.enabled = true;
}
private void timer1_tick(object sender, eventargs e)
{
try
{
if (server1.pending() == true)
{
col = server1.accepttcpclient();
arr.add(col);
xuliehua.serverjieshou server = new serverjieshou(col, arr);
lianjie.add(server);
}
if (arr.count == 0) { return; }
listbox1.items.clear();
foreach (tcpclient col in arr)
{
ipendpoint ip = (ipendpoint)col.client.remoteendpoint;
listbox1.items.add(ip.tostring());
}
}
catch (exception err)
{
messagebox.show(err.message);
// application.exit();
}
}
private void frmserver_formclosing(object sender, formclosingeventargs e)
{
try
{
foreach (xuliehua.serverjieshou col in lianjie)
{
col.th.abort();
col.th.join();
}
foreach (tcpclient col in arr)
{
col.close();
}
}
finally
{
application.exit();
}
}
}
}
客户端
复制代码 代码如下:
using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.text;
using system.windows.forms;
using system.threading;
using system.runtime.serialization;
using system.runtime.serialization.formatters.binary;
using system.io;
using system.net;
using system.net.sockets;
using xuliehua;
namespace 客户端
{
public partial class frmclinet : form
{
public frmclinet()
{
initializecomponent();
}
private tcpclient clinet;
private networkstream net;
private void button3_click(object sender, eventargs e)
{
try
{
clinet = new tcpclient();
clinet.connect(dns.gethostaddresses(textbox2.text)[0], 8000);
this.text = "服务器连接成功";
thread th = new thread(new threadstart(jieshou));
th.start();
timer1.enabled = true;
}
catch (socketexception)
{
clinet.close();
clinet = null;
}
}
private void jieshou()
{
try
{
while(clinet != null)
{
net = clinet.getstream();
if (net.canwrite == false) { clinet = null; return;}
if (net.dataavailable == true)
{
byte[] tmp = new byte[1024];
memorystream memory = new memorystream();
int len = 1;
while (len != 0)
{
if (net.dataavailable == false) { break; }
len = net.read(tmp, 0, tmp.length);
memory.write(tmp, 0, len);
}
if (memory.toarray().length != 4)
{
netmsg msg = (netmsg)xulie.bytetoobj(memory.toarray());
textbox1.text += msg.fip.tostring() + "说: " + msg.msg + "\r\n";
}
}
thread.sleep(200);
}
}
catch (exception err)
{
lock (textbox1)
{
textbox1.text = err.message;
}
}
}
private void frmclinet_formclosing(object sender, formclosingeventargs e)
{
if (net.canwrite == true)
{
netmsg msg = new netmsg();
msg.msg = "quit";
byte[] tmp = xulie.objtobyte(msg);
try
{
net.write(tmp, 0, tmp.length);
}
catch (ioexception)
{
textbox1.text += "已经从服务器断开连接\r\n";
clinet.close();
clinet = null;
return;
}
}
clinet = null;
gc.collect();
application.exitthread();
}
private void button1_click(object sender, eventargs e)
{
try
{
if (clinet != null)
{
if (net != null)
{
netmsg msg = new netmsg();
msg.fip = dns.gethostaddresses(dns.gethostname())[0];
msg.jieip = dns.gethostaddresses(textbox3.text)[0];
msg.msg = textbox4.text;
byte[] tmp = xulie.objtobyte(msg);
net.write(tmp, 0, tmp.length);
}
}
else
{
textbox1.text += "未与服务器建立连接\r\n";
}
}
catch (exception)
{
textbox1.text += "未与服务器建立连接\r\n";
}
}
private void timer1_tick(object sender, eventargs e)
{
try
{
if (clinet != null)
{
if (net.canwrite == true)
{
netmsg msg = new netmsg();
msg.msg = "0000";
byte[] tmp = xulie.objtobyte(msg);
try
{
net.write(tmp, 0, tmp.length);
}
catch (ioexception)
{
textbox1.text += "已经从服务器断开连接\r\n";
clinet.close();
clinet = null;
return;
}
}
}
else
{
textbox1.text += "未与服务器建立连接\r\n";
}
}
catch (exception err)
{
textbox1.text += err.message +"r\n";
}
}
}
}
您可能感兴趣的文章:
如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!
网友评论