socket开发,多终端,小数据量,应该采用什么方式好些.
private void button1_Click ( object sender , System.EventArgs e )
{
ListBox1.Items .Add ( "服务已经启动! " ) ;
_thread1 = new Thread ( new ThreadStart ( Listen ) ) ;
_thread1.Start ( ) ;
}
private void Listen ( )
{
//创建一个tcpListener对象,此对象主要是对给定端口进行侦听
tcpListener = new TcpListener(iPort);
//开始侦听
tcpListener.Start();
//返回可以用以处理连接的Socket实例
socketForClient = tcpListener.AcceptSocket ( ) ;
//如果返回值是 "true ",则产生的套节字已经接受来自远方的连接请求
if ( socketForClient.Connected )
{
ListBox1.Items.Add ( "已经和客户端成功连接! " ) ;
bool isOKa = true;
while ( true )
{
try
{
//创建networkStream对象通过网络套节字来接受和发送数据
networkStream = new NetworkStream ( socketForClient ) ;
//从当前数据流中读取一行字符,返回值是字符串
streamReader = new StreamReader (networkStream,Encoding.ASCII) ;
byte[] byteMessage=new byte[1024];
string msg = " ";
int bytes;
bytes = socketForClient.Receive(byteMessage,byteMessage.Length,0);
msg += Encoding.ASCII.GetString(byteMessage, 0, bytes);
ListBox1.Items.Add ( "收到客户端信息: " + msg + ": ") ;
log( "收到客户端信息: " + msg);
streamWriter = new StreamWriter ( networkStream,Encoding.ASCII ) ;
int iMsgLen = msg.Length;
SI.SocketInterfaceLogic.General myG = new SI.SocketInterfaceLogic.General();
string Cur_time = myG.SIdatetime(System.DateTime.Now);
string strHead = msg.Substring(0,10).Trim();
SI.SocketInterfaceLogic.Head myHead = new SI.SocketInterfaceLogic.Head(strHead);
int bodyLen = myG.SIintToint(myHead.command_length)-10;
string strBody = msg.Substring(10,bodyLen);
switch(myHead.func_no.Trim())
{
//公话认证,下发1
case "10 ":
//往当前的数据流中写入一行字符串
streamWriter.WriteLine( "001110 "+myHead.seq_no+ "1 ",Encoding.ASCII);
this.ListBox1.Items.Add( "001110 "+myHead.seq_no+ "1 ");
//刷新当前数据流中的数据
streamWriter.Flush( );
break;
//ST