using
System;
using
System.Collections;
using
System.Collections.Generic;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Text;
using
System.Windows.Forms;
using
System.Net;
using
System.Net.Sockets;
using
System.Threading;
using
System.IO;
using
System.Configuration;

namespace
SocketSever

...
{
public partial class MainForm : Form

...{

业务操作#region 业务操作

bool isStop = true;

Thread theadone = null;
Socket listener=null;
int serverPort

...{
get

...{
int tmpPort=*;//隱藏掉了自己添加
try

...{
tmpPort = int.Parse(ConfigurationSettings.AppSettings["serverPort"]);
}
catch (Exception ex)

...{
tmpPort = *;
}
return tmpPort;
}

}

private string serverIp()

...{
string ipStr=string.Empty;
ipStr = "服务器可用IP:";
IPHostEntry serverEntry = Dns.Resolve(Dns.GetHostName());
IPAddress[] ipArr= Dns.GetHostAddresses(Dns.GetHostName());
try

...{
for (int i = 0; i < serverEntry.AddressList.Length; i++)

...{
ipStr += "&" + serverEntry.AddressList[i] +" ";

}
}
catch (Exception ex)

...{
//MessageBox.Show(ex.Message);
}
return ipStr;
}

public static ManualResetEvent doneAll = new ManualResetEvent(false);



/**//// <summary>
/// 监听程序
/// </summary>
public void StarListening()

...{
IPHostEntry ipentry = Dns.Resolve(Dns.GetHostName());
IPAddress ipaddr = ipentry.AddressList[0];
IPEndPoint ipEndp = new IPEndPoint(ipaddr, serverPort);

listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try

...{

listener.Bind(ipEndp);
listener.Listen(50);
while (true)

...{
doneAll.Reset();
lblStates.Text = "等待连接...";
txtLog.Text = "时间" + DateTime.Now + " 开始服务 " + txtLog.Text;

//进行移步调用.
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);

doneAll.WaitOne();
}

}
catch (Exception ex)

...{
//MessageBox.Show(ex.Message,"错误信息");
Abort();
}
}


//接受数据
public void AcceptCallback(IAsyncResult iar)

...{
try

...{
doneAll.Set();

Socket listener = (Socket)iar.AsyncState;
Socket handler = listener.EndAccept(iar);

StateObj state = new StateObj();
//开始接受数据
state.WorkSocket = handler;
handler.BeginReceive(state.buffer, 0, state.bufferSize, 0,
new AsyncCallback(ReakCallback), state);
}
catch (Exception ex)

...{
//MessageBox.Show(ex.Message);
Abort();
}
}



/**//// <summary>
/// 移步接受
/// </summary>
/// <param name="iar"></param>
public void ReakCallback(IAsyncResult iar)

...{
string contxt = string.Empty;
StateObj state = (StateObj)iar.AsyncState;
Socket handler = state.WorkSocket;
//handler.EndAccept(out state.buffer,iar);
try

...{
int readBytes = handler.EndReceive(iar);

if (readBytes > 0)

...{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, readBytes));
contxt = state.sb.ToString();
if (contxt.IndexOf(@"#") > -1)

...{
txtLog.Text = "时间" + DateTime.Now + " 接收的信息: " + contxt + " " + txtLog.Text; ;
// Echo the data back to the client.
//Send(handler, contxt);
Send(handler, voteResult(contxt));
lblStates.Text = "数据接收完毕..";
}
else

...{
handler.BeginReceive(state.buffer, 0, state.bufferSize, 0, new AsyncCallback(ReakCallback), state);
lblStates.Text = "数据接受中...";
}
}
}
catch(Exception ex)

...{
//handler.BeginReceive(state.buffer, 0, state.bufferSize, 0, new AsyncCallback(ReakCallback), state);
//lblStates.Text = "数据接受中...";
}
}



/**//// <summary>
/// 发送
/// </summary>
/// <param name="handler"></param>
/// <param name="Contxt"></param>
private void Send(Socket handler, string Contxt)

...{
if (!handler.Connected)

...{
lblStates.Text = "没有客户端连接";
}
else

...{
byte[] byteData = Encoding.ASCII.GetBytes(Contxt);
txtLog.Text = "时间" + DateTime.Now + ":准备发送内容 ["+Contxt +"] "+ txtLog.Text;
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
}
}


/**//// <summary>
/// 发送反馈
/// </summary>
/// <param name="iar"></param>
private void SendCallback(IAsyncResult iar)

...{
try

...{
Socket handler = (Socket)iar.AsyncState;
int sendByte = handler.EndSend(iar);
txtLog.Text = "时间" + DateTime.Now +" ["+sendByte + "] bytes发送 " + txtLog.Text;
lblStates.Text = "数据发送完毕..";
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception ex)

...{
//MessageBox.Show(ex.Message.ToString(),"错误信息");
}
}


/**//// <summary>
/// 停止线程和监听
/// </summary>
/// <param name="iar"></param>
private void Abort()

...{
if (theadone != null)

...{
try

...{
theadone.Abort();
if (theadone != null)

...{
theadone = null;
}
listener.Close();
if (listener != null)

...{ listener = null;}
}
catch (Exception ex)

...{
//MessageBox.Show(ex.Message);
}
}
}


/**//// <summary>
/// 执行监听
/// </summary>
private void RunThead()

...{
if (isStop)

...{
theadone = new Thread(new ThreadStart(StarListening));
theadone.Name = "Listen.Port";
theadone.Start();
isStop = false;
}
else

...{
MessageBox.Show("程序已运行", "错误操作");
}
}
#endregion


窗体操作#region 窗体操作

/**//// <summary>
/// 释放窗体资源
/// </summary>
private void ReleaseFrom()

...{
try

...{
if (theadone != null)

...{
theadone.Abort();
}
}
catch

...{
}
this.Dispose();
base.Dispose();
}


/**//// <summary>
/// 窗体显示操作
/// </summary>
private void FormShow()

...{
if (WindowState == FormWindowState.Minimized)

...{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
//Sys_NF.Visible = true;
}
if (WindowState == FormWindowState.Normal)

...{
this.Visible = false;
this.WindowState = FormWindowState.Minimized;
//Sys_NF.Visible = false;
}
}


/**//// <summary>
/// 窗体显示操作
/// </summary>
private void FormShowIco()

...{
if (WindowState == FormWindowState.Minimized)

...{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
//Sys_NF.Visible = true;
}
if (WindowState == FormWindowState.Normal)

...{
this.Visible = false;
this.WindowState = FormWindowState.Minimized;
//Sys_NF.Visible = false;
}
}

#endregion


控件设定#region 控件设定
public MainForm()

...{
InitializeComponent();
}

private void Sys_NF_MouseDoubleClick(object sender, MouseEventArgs e)

...{
if (WindowState == FormWindowState.Minimized)

...{
this.Visible = true;
this.WindowState = FormWindowState.Normal;
Sys_NF.Visible = true;
}
else

...{
this.Visible = false;
this.WindowState = FormWindowState.Minimized;
Sys_NF.Visible = true;
}
}

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)

...{
this.ReleaseFrom();
}

private void Sys_Out_Click(object sender, EventArgs e)

...{
if (isStop)

...{
this.Close();
}
else

...{
MessageBox.Show("请先停止服务器","提示!");
}
}

private void NFTool_ShowForm_Click(object sender, EventArgs e)

...{
this.FormShow();
}

private void MainForm_Load(object sender, EventArgs e)

...{

lblSysinformation.Text = serverIp();
Thread runThead = new Thread(new ThreadStart(RunThead));
runThead.Start();
Thread.Sleep(1000);
}

private void Sys_Run_Click(object sender, EventArgs e)

...{
RunThead();
}

private void Sys_Stop_Click(object sender, EventArgs e)

...{
if (!isStop)

...{
Abort();
txtLog.Text = "时间" + DateTime.Now + "停止服务 " + txtLog.Text;
lblStates.Text = "停止监听..";
isStop = true;
}
else

...{
MessageBox.Show("程序已停止","错误操作");
}
}

private void Log_Clear_Click(object sender, EventArgs e)

...{
txtLog.Text = "";
}

private void Log_Save_Click(object sender, EventArgs e)

...{
saveDg.ShowDialog();

}

private void saveDg_FileOk(object sender, CancelEventArgs e)

...{
SaveLog();
}

private void SaveLog()

...{
string fileName=saveDg.FileName;
StreamWriter sw = new StreamWriter(fileName);
sw.Write(txtLog.Text.Trim());
sw.WriteLine(" =========="+DateTime.Now + ",接口日志保存============================================== ");
sw.Close();
MessageBox.Show("日志保存成功");

}

private void US_Help_Click(object sender, EventArgs e)

...{
System.Diagnostics.Process.Start("#");
}

private void US_about_Click(object sender, EventArgs e)

...{
MessageBox.Show("接口程序服务器端","关于我们");
}

private void Sys_PortSetting_Click(object sender, EventArgs e)

...{
MessageBox.Show("未实现","服务器端口设定");
}
#endregion


投票操作#region 投票操作

/**//// <summary>
/// 投票
/// </summary>
/// <param name="contxt"></param>
/// <returns></returns>
private string voteResult(string contxt)

...{
Receive rec = new Receive();
return rec.voteResult(rec.contxtArry(contxt, "",''));//處理接受信息的方法.
}
#endregion
}
}
以上代碼是主程序用到的.由于這個東東在運行所以有些信息不便透露.
下面是其他的類.
using
System;
using
System.Data;
using
System.Configuration;
using
System.Net;
using
System.Net.Sockets;
using
System.Text;
namespace
SocketSever

...
{

/**//// <summary>
/// 套接字状态类
/// </summary>
public class StateObj

...{

/**//// <summary>
/// 套接字对象
/// </summary>
public Socket WorkSocket = null;


/**//// <summary>
/// 套接字内存大小
/// </summary>
public int bufferSize = 1024;


/**//// <summary>
/// 套接字内存字节数组
/// </summary>
public byte[] buffer = new byte[1024];


/**//// <summary>
/// 套接字接受到的信息
/// </summary>
public StringBuilder sb = new StringBuilder();
}
}
這個是管理狀態的.
下面這個是處理業務的
using
System;
using
System.Collections.Generic;
using
System.Text;
using
System.Collections;
using
SocketSever.DLL;

namespace
SocketSever

...
{
public class Receive

...{

/**//// <summary>
/// 获取投票信息
/// </summary>
/// <param name="contxt">内容</param>
/// <param name="endStr">结束符</param>
/// <returns></returns>
public string[] contxtArry(string contxt, string endStr,char separator)

...{

string[] tmparr = new string[3] ...{ "","",""};
contxt=contxt.Replace(endStr, "").Trim();
if (contxt.IndexOf(separator.ToString()) > -1)

...{
string[] tmp = contxt.Split(separator);
for (int i = 0; i < tmp.Length; i++)

...{
tmparr[i] = tmp[i];
}
}
return tmparr;
}


/**//// <summary>
/// 投票
/// </summary>
/// <param name="contxt">必须是contxtArry</param>
/// <returns></returns>
public string voteResult(string[] contxt)

...{
Rules Rule = new Rules();
string statement = string.Empty;
string Number = string.Empty;
int tiCount = 0;
if (contxt[0] != string.Empty)

...{
statement = contxt[0];
}
if (contxt[2] != string.Empty)

...{
try

...{
tiCount = Convert.ToInt32(contxt[2]);
}
catch

...{
tiCount = 1;
}
}
else

...{
tiCount = 1;
}
if (contxt[1] != string.Empty)

...{
Number = contxt[1];
try

...{
if (Number != string.Empty)

...{
return Rule.isVote(Number, statement, tiCount);
}
else

...{
return "404";
}
}
catch (Exception ex)

...{
return "500.100";
}
}
else

...{
return "000";
}
}
}
}
就這樣俺就完成了這次開發,唉.....
悶~~~.
沒有激情...