做了一个server类,和client类,采用tcp协议通讯。client发送一个command给server,server反馈一个信息给client.
public server
{
listener=new TcpListener(8080);
listener.Start();
this.server=new Thread(new ThreadStart(run));
this.server.Start();
}
public void run()
{
s=listener.AcceptSocket();
NetworkStream ns=new NetworkStream(s);
StreamReader sr=new StreamReader(ns);
while(true)
{
string result;
string command=sr.ReadLine();
switch(command)
{
....
}
if(result!=null)
{
textBox1.Text=textBox1.Text+" * * "+result;
Byte[] res=System.Text.Encoding.ASCII.GetBytes(result.ToCharArray());
s.Send(res);
}
}
public client(string host,int port,bool releasecon)
{
this.port=port;
this.host=host;
this.releasecon=releasecon;
if(!this.releasecon)
{
this.client=new TcpClient(this.host,this.port);
this.outstr=this.client.GetStream();
this.instr=new StreamReader(this.outstr);
MessageBox.Show("using hold mode");
}
else
{MessageBox.Show("using release mode");
}
}
public bool excute(string command,ref string result)
{
bool ret=true;
com=command;
if(this.releasecon)
{
this.client=new TcpClient(this.host,this.port);
this.outstr=this.client.GetStream();
this.instr=new StreamReader(this.outstr);
//MessageBox.Show("connecting to "+this.host+":" +this.port);
}
com+="\r\n";
Byte[] cmd=System.Text.Encoding.ASCII.GetBytes(com.ToCharArray());
this.outstr.Write(cmd,0,cmd.Length);
result=this.instr.ReadLine();
MessageBox.Show("client:result:"+result);
if(this.releasecon)
{
this.client.Close();
}
ret=!result.Equals("byebye");
return ret;
}
}
}
运行时client发送给server的消息server 收到了,但server反馈的信息client无法收到。经跟踪发现程序运行到excute的
result=this.instr.ReadLine();程序死在那里无法进行。怎样解决?请多指教。
服务器发送时,请加上"\r\n"
否则readline不会读。
试试看
你把整个代码发到我的邮箱。
我帮你看看。
aspnet163@hotmail.com
下面的例子没问题
//开始监听
private void btnListen_Click(object sender, System.EventArgs e)
{
try
{
IPHostEntry myHost = new IPHostEntry();
myHost = Dns.GetHostByName(txtServer.Text);
string IPstring = myHost.AddressList[0].ToString();
myIP = IPAddress.Parse(IPstring);
}
catch
{
MessageBox.Show("您输入的IP地址格式不正确,请重新输入!");
}
try
{
myServer = new IPEndPoint(myIP,Int32.Parse(txtPort.Text.Trim()));
mySocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
mySocket.Bind(myServer);
mySocket.Listen(50);
//IPEndPoint aaIP = (IPEndPoint)mySocket.LocalEndPoint;
//int aa = aaIP.Port;
//MessageBox.Show(aa.ToString());
txtState.AppendText("主机"+txtServer.Text+"端口"+txtPort.Text+"开始监听.....\r\n");
//线程
Thread thread = new Thread(new ThreadStart(target));
thread.Start();
}
catch(Exception ee)
{
txtState.AppendText(ee.Message+"\r\n");
}
}
//线程同步方法target
private void target()
{
while(true)
{
//设为非终止
myReset.Reset();
mySocket.BeginAccept(new AsyncCallback(AcceptCallback),mySocket);
//阻塞当前线程,直到收到请求信号
myReset.WaitOne();
}
}
//异步回调方法AcceptCallback
private void AcceptCallback(IAsyncResult ar)
{
//将事件设为终止
myReset.Set();
Socket listener = (Socket)ar.AsyncState;
handler = listener.EndAccept(ar);
//获取状态
StateObject state = new StateObject();
state.workSocket = handler;
txtState.AppendText("与客户建立连接。\r\n");
try
{
byte[] byteData = System.Text.Encoding.BigEndianUnicode.GetBytes("已经准备好,请通话!"+"\r\n");
//开始发送
handler.BeginSend(byteData,0,byteData.Length,0,new AsyncCallback(SendCallback),handler);
}
catch(Exception ee)
{
MessageBox.Show(ee.Message);
}
//线程
Thread thread = new Thread(new ThreadStart(begReceive));
thread.Start();
}
//异步回调方法 SendCallback
private void SendCallback(IAsyncResult ar)
{
try
{
handler = (Socket)ar.AsyncState;
int bytesSent = handler.EndSend(ar);
}
catch(Exception ee)
{
MessageBox.Show(ee.Message);
}
}
//线程同步方法begReceive
private void begReceive()
{
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer,0,StateObject.BufferSize,0,new AsyncCallback(ReadCallback),state);
}
//异步回调方法ReadCallback
private void ReadCallback(IAsyncResult ar)
{
StateObject state = (StateObject) ar.AsyncState;
Socket tt = state.workSocket;
//结束读取并获取读取字节数
int bytesRead = handler.EndReceive(ar);
state.sb.Append(System.Text.Encoding.BigEndianUnicode.GetString(state.buffer,0,bytesRead));
string content = state.sb.ToString();
state.sb.Remove(0,content.Length);
rtbIncept.AppendText(content+"\r\n");
//重新开始读取数据
tt.BeginReceive(state.buffer,0,StateObject.BufferSize,0,new AsyncCallback(ReadCallback),state);
}
#endregion 监听
//发送信息
private void btnSend_Click(object sender, System.EventArgs e)
{
try
{
byte[] byteData = System.Text.Encoding.BigEndianUnicode.GetBytes(rtbSend.Text+"\r\n");
//开始发送数据
handler.BeginSend(byteData,0,byteData.Length,0,new AsyncCallback(SendCallback),handler);
}
catch(Exception ee)
{
MessageBox.Show(ee.Message);
}
}
//停止监听
private void btnStop_Click(object sender, System.EventArgs e)
{
try
{
mySocket.Close();
txtState.AppendText("主机"+txtServer.Text+"端口"+txtPort.Text+"停止监听"+"\r\n");
}
catch
{
MessageBox.Show("监听尚未开始,关闭无效!");
}
}