做一个项目用Socket连接服务器。Send操作信息之后再调用接收服务器信息的代码。无法接收服务器返回的信息。
必须中间加个MessageBox.Show("");卡下程序才能接收到信息为什么啊?
代码如下:
客户端的Socket
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net.Sockets;namespace Shentangtech.Pub
{
public class ClientSocket
{
private TcpClient client;
private const int BUFFER_SIZE = 10240;
private bool acitve = false;
private bool reConn = false; public bool ReConn
{
get { return reConn; }
set { reConn = value; }
} public delegate void conncetDelegate(bool hasConn);//连接事件
public delegate void disconncetDelegate();//断开事件
public delegate void receiveDelegeate(String msg);//接收事件 //public event conncetDelegate OnConnect;
//public event disconncetDelegate OnDisconnect;
public event receiveDelegeate OnReceive; //是否已连接
public bool Connected
{
get { return acitve; }
}
//连接指定的服务器
public void ConnectServer(String host, int port)
{
try
{
client = new TcpClient();
client.Connect(host, port);
acitve = true;
Thread rd = new Thread(new ThreadStart(Receive));
rd.IsBackground = true;
rd.Start();
//OnConnect(true);
}
catch
{
try
{
client.Client.Close();
}
catch { }
client = null;
acitve = false;
//OnConnect(false);
}
}
//断开连接
public void DisConnect()
{
acitve = false;
try
{
client.Client.Shutdown(SocketShutdown.Both);
client.Client.Close();
client.Close();
}
catch { }
}
//断开连接
public void ForceDisConnect()
{
acitve = false;
reConn = false;
try
{
client.Client.Shutdown(SocketShutdown.Both);
client.Client.Close();
client.Close();
}
catch { }
}
//接收线程
private void Receive()
{
client.Client.SendBufferSize = BUFFER_SIZE;
client.Client.ReceiveBufferSize = BUFFER_SIZE;
while(acitve)
{
try
{
byte[] buffer = new byte[BUFFER_SIZE];
int count = client.Client.Receive(buffer);
if(count == 0)
break;
String s = Encoding.UTF8.GetString(buffer, 0, count);
//Console.WriteLine("rec:" + s);
OnReceive(s);
}
catch { break; }
}
try
{
client.Client.Close();
}
catch { }
client = null;
//OnDisconnect();
}
//发送
public bool Send(String msg)
{
try
{
client.Client.Send(Encoding.UTF8.GetBytes(msg.ToCharArray()));
//Console.WriteLine("send:" + msg);
return true;
}
catch
{
try
{
client.Client.Close();
}
catch{}
return false;
}
}
}
}客户端发送请求信息:
public void C_Company_List()
{
StringBuilder stb = new StringBuilder(Constant.HEAD).Append(Constant.C_COMPANY).Append(Constant.C_COMPANY_LIST);
if (Global.UserType == "0")
{
stb.Append("0").Append(Constant.FOOT);
}
else
{
stb.Append(Global.CompanyID.ToString()).Append(Constant.FOOT);
} dataSocket.Send(stb.ToString());
DataOnReceive();
}处理接收信息的方法:
//处理从服务器端发来的字符串
public void DataOnReceive()
{
try
{
String rec = RecStr;
if (rec.IndexOf(Constant.HEAD) == 0 && rec.IndexOf(Constant.FOOT) > Constant.HEAD.Length)
{
rec = rec.Substring(0, rec.LastIndexOf(Constant.FOOT) + Constant.FOOT.Length);
RecStr = RecStr.Substring(rec.Length);
}
else rec = "";
while (rec.IndexOf(Constant.HEAD) == 0 && rec.IndexOf(Constant.FOOT) > Constant.HEAD.Length)
{
String line = rec.Substring(Constant.HEAD.Length, rec.IndexOf(Constant.FOOT) - Constant.HEAD.Length);//取去除头尾的有效字段
rec = rec.Substring(rec.IndexOf(Constant.FOOT) + Constant.FOOT.Length);
char key1 = line[0];
char key2 = line[1];
line = line.Substring(2);
if (line.Length == 0)
{
break;
}
if (key1 == Constant.C_CARINFO)
{
switch (key2)
{
case Constant.C_CARINFO_LIST:
C_CarInfo_R_List(line);
break;
}
}
else if (key1 == Constant.C_CARGROUP)
{
switch (key2)
{
case Constant.C_CARGROUP_LIST:
C_CarGroup_R_List(line);
break;
}
}
else if (key1 == Constant.C_COMPANY)
{
switch (key2)
{
case Constant.C_COMPANY_LIST:
C_Company_R_List(line);
break;
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
必须中间加个MessageBox.Show("");卡下程序才能接收到信息为什么啊?
代码如下:
客户端的Socket
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net.Sockets;namespace Shentangtech.Pub
{
public class ClientSocket
{
private TcpClient client;
private const int BUFFER_SIZE = 10240;
private bool acitve = false;
private bool reConn = false; public bool ReConn
{
get { return reConn; }
set { reConn = value; }
} public delegate void conncetDelegate(bool hasConn);//连接事件
public delegate void disconncetDelegate();//断开事件
public delegate void receiveDelegeate(String msg);//接收事件 //public event conncetDelegate OnConnect;
//public event disconncetDelegate OnDisconnect;
public event receiveDelegeate OnReceive; //是否已连接
public bool Connected
{
get { return acitve; }
}
//连接指定的服务器
public void ConnectServer(String host, int port)
{
try
{
client = new TcpClient();
client.Connect(host, port);
acitve = true;
Thread rd = new Thread(new ThreadStart(Receive));
rd.IsBackground = true;
rd.Start();
//OnConnect(true);
}
catch
{
try
{
client.Client.Close();
}
catch { }
client = null;
acitve = false;
//OnConnect(false);
}
}
//断开连接
public void DisConnect()
{
acitve = false;
try
{
client.Client.Shutdown(SocketShutdown.Both);
client.Client.Close();
client.Close();
}
catch { }
}
//断开连接
public void ForceDisConnect()
{
acitve = false;
reConn = false;
try
{
client.Client.Shutdown(SocketShutdown.Both);
client.Client.Close();
client.Close();
}
catch { }
}
//接收线程
private void Receive()
{
client.Client.SendBufferSize = BUFFER_SIZE;
client.Client.ReceiveBufferSize = BUFFER_SIZE;
while(acitve)
{
try
{
byte[] buffer = new byte[BUFFER_SIZE];
int count = client.Client.Receive(buffer);
if(count == 0)
break;
String s = Encoding.UTF8.GetString(buffer, 0, count);
//Console.WriteLine("rec:" + s);
OnReceive(s);
}
catch { break; }
}
try
{
client.Client.Close();
}
catch { }
client = null;
//OnDisconnect();
}
//发送
public bool Send(String msg)
{
try
{
client.Client.Send(Encoding.UTF8.GetBytes(msg.ToCharArray()));
//Console.WriteLine("send:" + msg);
return true;
}
catch
{
try
{
client.Client.Close();
}
catch{}
return false;
}
}
}
}客户端发送请求信息:
public void C_Company_List()
{
StringBuilder stb = new StringBuilder(Constant.HEAD).Append(Constant.C_COMPANY).Append(Constant.C_COMPANY_LIST);
if (Global.UserType == "0")
{
stb.Append("0").Append(Constant.FOOT);
}
else
{
stb.Append(Global.CompanyID.ToString()).Append(Constant.FOOT);
} dataSocket.Send(stb.ToString());
DataOnReceive();
}处理接收信息的方法:
//处理从服务器端发来的字符串
public void DataOnReceive()
{
try
{
String rec = RecStr;
if (rec.IndexOf(Constant.HEAD) == 0 && rec.IndexOf(Constant.FOOT) > Constant.HEAD.Length)
{
rec = rec.Substring(0, rec.LastIndexOf(Constant.FOOT) + Constant.FOOT.Length);
RecStr = RecStr.Substring(rec.Length);
}
else rec = "";
while (rec.IndexOf(Constant.HEAD) == 0 && rec.IndexOf(Constant.FOOT) > Constant.HEAD.Length)
{
String line = rec.Substring(Constant.HEAD.Length, rec.IndexOf(Constant.FOOT) - Constant.HEAD.Length);//取去除头尾的有效字段
rec = rec.Substring(rec.IndexOf(Constant.FOOT) + Constant.FOOT.Length);
char key1 = line[0];
char key2 = line[1];
line = line.Substring(2);
if (line.Length == 0)
{
break;
}
if (key1 == Constant.C_CARINFO)
{
switch (key2)
{
case Constant.C_CARINFO_LIST:
C_CarInfo_R_List(line);
break;
}
}
else if (key1 == Constant.C_CARGROUP)
{
switch (key2)
{
case Constant.C_CARGROUP_LIST:
C_CarGroup_R_List(line);
break;
}
}
else if (key1 == Constant.C_COMPANY)
{
switch (key2)
{
case Constant.C_COMPANY_LIST:
C_Company_R_List(line);
break;
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
服务器端Socket:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Net.Sockets;namespace STGPSServer
{
public class ClientSocket
{
private int id = 10000;
private TcpClient client = null;
private const int BUFFER_SIZE = 10240;
private bool acitve = false;
private bool reConn = false;
private bool hasLogin = false;
private bool testOk = false;
private bool needTest = false; public bool NeedTest
{
get { return needTest; }
set { needTest = value; }
}
public bool TestOk
{
get { return testOk; }
set { testOk = value; }
}
public bool HasLogin
{
get { return hasLogin; }
set { hasLogin = value; }
}
public bool ReConn
{
get { return reConn; }
set { reConn = value; }
} public delegate void conncetDelegate(int n, bool hasConn);//连接事件
public delegate void disconncetDelegate(int n);//断开事件
public delegate void receiveDelegeate(int n, String msg);//接收事件 public event conncetDelegate OnConnect;
public event disconncetDelegate OnDisconnect;
public event receiveDelegeate OnReceive; public ClientSocket(int i)
{
id = i;
}
//是否已连接
public bool Connected
{
get { return acitve; }
}
//连接指定的服务器
public void ConnectServer(String host, int port)
{
try
{
client = new TcpClient();
client.Connect(host, port);
acitve = true;
Thread rd = new Thread(new ThreadStart(Receive));
rd.Name = "client_socket_rev_" + id;
rd.IsBackground = true;
rd.Start();
if(OnConnect != null)
OnConnect(id, true);
}
catch
{
try
{
client.Client.Close();
}
catch { }
client = null;
acitve = false;
if(OnConnect != null)
OnConnect(id, false);
}
}
//断开连接
public void DisConnect()
{
acitve = false;
}
//断开连接
public void ForceDisConnect()
{
acitve = false;
reConn = false;
}
//接收线程
private void Receive()
{
client.Client.SendBufferSize = BUFFER_SIZE;
client.Client.ReceiveBufferSize = BUFFER_SIZE;
while(acitve)
{
try
{
byte[] buffer = new byte[BUFFER_SIZE];
int count = client.Client.Receive(buffer);
if(count == 0)
break;
String s = Encoding.UTF8.GetString(buffer, 0, count);
if(OnReceive != null)
OnReceive(id, s);
//Console.WriteLine("rec sms:" + s);
}
catch { break; }
}
try
{
client.Client.Close();
}
catch { }
client = null;
acitve = false;
if(OnDisconnect != null)
OnDisconnect(id);
}
//发送
public bool Send(String msg)
{
try
{
client.Client.Send(Encoding.UTF8.GetBytes(msg.ToCharArray()));
//Console.WriteLine("send to sms:" + msg);
return true;
}
catch
{
try
{
client.Client.Close();
}
catch{}
return false;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Threading;namespace STGPSServer
{
class ServerSocket
{
private int port = 0;
private bool active = false;
private Encoding encoding = null;
private TcpListener listener;
private List<Socket> socketList = new List<Socket>(); public delegate void activeDelegate(bool actived);
public delegate void deactiveDelegate();
public delegate void conncetDelegate(Socket socket);
public delegate void disconncetDelegate(Socket socket);
public delegate void receiveDelegeate(Socket socket, String msg);
public delegate void receiveDelegeateEx(Socket socket, String msg); public event activeDelegate OnActive;
public event deactiveDelegate OnDeactive;
public event conncetDelegate OnConnect;
public event disconncetDelegate OnDisconnect;
public event receiveDelegeate OnReceive;
public event receiveDelegeateEx OnReceiveEx;
//端口设置
public int Port
{
get { return port; }
set
{
if(!active)
port = value;
}
}
//解码/编码方式
public Encoding Encoding
{
get { return encoding; }
set { encoding = value; }
}
//启动/关闭服务
public bool Active
{
get { return active; }
set
{
if(active && !value)
{
active = false;
try
{
listener.Server.Close();
}
catch { }
}
else if(!active && value)
{
listener = new TcpListener(port);
try
{
active = true;
listener.Start();
Thread rd = new Thread(new ThreadStart(Listen));
rd.Name = "server_socket_listen";
//rd.IsBackground = true;
rd.Start();
if(OnActive != null)
OnActive(true);
}
catch
{
try
{
listener.Stop();
}
catch { }
if(OnActive != null)
OnActive(false);
}
}
}
}
//关闭指定的连接
public void CloseConnection(Socket socket)
{
foreach(Socket st in socketList)
if(socket == st)
{
try
{
st.Close();
}
catch { }
break;
}
} #region 内部线程
//监听端口
private void Listen()
{
while(active)
{
try
{
Socket newSocket = listener.AcceptSocket();
Thread rd = new Thread(new ThreadStart(ClientRun));
socketList.Add(newSocket);
rd.Name = (socketList.Count - 1).ToString();
rd.IsBackground = true;
if(OnConnect != null)
OnConnect(newSocket);
rd.Start();
}
catch{ break; }
}
active = false;
try
{
foreach(Socket st in socketList)
{
try
{
st.Close();
}
catch { }
}
}
catch { }
listener = null;
if(OnDeactive != null)
OnDeactive();
}
//接收线程
private void ClientRun()
{
Socket socket = null;
try
{
socket = socketList[Int32.Parse(Thread.CurrentThread.Name)];
socket.SendBufferSize = 10240;
socket.ReceiveBufferSize = 10240;
while(socket.Connected && active)
{
try
{
String rec = "";
byte[] buffer = new byte[10240];
int count = socket.Receive(buffer);
if(count == 0)
break;
if(encoding != null)
{
rec = this.Encoding.GetString(buffer, 0, count);
if(rec == Constant.CONN_TEST)
{
socket.Send(this.Encoding.GetBytes(Constant.CONN_TEST));
}
else
{
if(OnReceive != null)
OnReceive(socket, rec);
}
}
else if(OnReceiveEx != null)
{
StringBuilder stb = new StringBuilder();
for(int i = 0; i < count; i++)
{
stb.Append((char)(buffer[i]));
}
OnReceiveEx(socket, stb.ToString());
}
}
catch{}
}
}
catch{}
if(active)
{
try
{
socket.Disconnect(false);
}
catch { }
try
{
socket.Close();
}
catch { }
}
if(OnDisconnect != null)
OnDisconnect(socket);
socketList.Remove(socket);
}
#endregion }
}
private void data_RevMsg(Socket st, String mess)
{
try
{
//Console.WriteLine("rec:" + mess);
DataClient dataClient = null;
int index = 0;
while(index < dataClientList.Count)
{
if(dataClientList[index].Socket == st)
{
dataClient = dataClientList[index];
break;
}
index++;
}
if(dataClient == null)
return;
dataClient.RecStr = dataClient.RecStr + mess;
while(dataClient.RecStr.IndexOf(Constant.HEAD) == 0
&& dataClient.RecStr.IndexOf(Constant.FOOT) > Constant.HEAD.Length)
{
String msg = dataClient.RecStr.Substring(Constant.HEAD.Length, dataClient.RecStr.IndexOf(Constant.FOOT) - Constant.HEAD.Length);
dataClient.RecStr = dataClient.RecStr.Substring(dataClient.RecStr.IndexOf(Constant.FOOT) + Constant.FOOT.Length);
char key1 = msg[0];
if(key1 == Constant.C_TEST)
{
dataClient.ConnCount = 0;
C_Conn_Test(dataClient);
return;
}
char key2 = msg[1];
String line = msg.Substring(2);
if(key1 == Constant.C_CONN)
{
switch(key2)
{
case Constant.C_CONN_LOGIN:
C_Conn_Login(dataClient, line);
break;
case Constant.C_CONN_LOGOUT:
C_Conn_Logout(dataClient);
break;
}
}
}其中方法调用后回再次返回信息:
private void C_Info_UserList(DataClient dataClient, String rec)
{
try
{
StringBuilder stb = new StringBuilder(Constant.HEAD).Append(Constant.C_INFO).Append(Constant.C_INFO_USERLIST);
dataClient.Send(stb.ToString());
}只有我在客户端发送信息
dataSocket.Send(stb.ToString());
DataOnReceive();
中间加一句messagebox.show("1");
卡下程序才能接收到服务器端发送过来的信息。调试的时候在dataSocket.Send(stb.ToString());
之后服务器端有运行代码。也发送了。但是接收的为""空值只有加messagebox.show("1");
才行
就是变成
dataSocket.Send(stb.ToString());
messagebox.show("1");
DataOnReceive();
才能正确运行为什么呢?
怎么解决
messagebox.show("1");
DataOnReceive();
才能正确运行为什么呢?发送数据后,需要对方处理,不是及时的,不信
messagebox.show("1");改为Thread.sleep(100000)试试
现成的代码