我的客户代码:
void* Gameserver::listenSocketData(void* obj){
char buffer[5];
std::string contents;
int ret = 0;
bool rs = true;
int count=0;
while(rs)
{
contents = "";
send(m_socketHandle, "send from ios", 20, 0);
CCLog("send:%d",count++);
ret = recv(m_socketHandle,buffer,4,0);
CCLog("what ret:%d",ret);
// 服务器关闭
if(ret == 0)
{
CCLog("Error: server close");
rs = false;
}
if(ret == 4)
{
char buf[2000];
int start ;
int end ;
while((ret = recv(m_socketHandle,buf,10,0))>0)
{
contents.append(buf,ret);
break;
}
CCLog("stard:%d,end:%d",start,end);
CCLog("recv content:%s\n",contents.c_str());
CCString* str = CCString::create(contents.substr(start,end-start));
CCNotificationCenter::sharedNotificationCenter()->postNotification("receivedata", str);
}else {
CCLog("Error: recv data Error %d",ret);
}
}
return NULL;
}
我使用java socket作为服务器:
public void beginListen(){
while(true){
try{
final Socket socket = sever.accept();
new Thread(new Runnable(){
public void run(){
BufferedReader in;
try{
in = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
PrintWriter out = new PrintWriter(socket.getOutputStream());
while (!socket.isClosed()){
String str;
str = in.readLine();
out.println("Hello!world!! " + str);
out.flush();
if (str == null || str.equals("end"))
break;
System.out.println(str);
}
socket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}).start();
}catch(IOException e){
e.printStackTrace();
}
}
}
并且奇怪的是,如果我只使用发送功能,服务器可以接收消息,所以我认为服务器没问题。但是如果我在客户端同时使用send和recv,只有当我退出客户端时,服务器才能打印收到的消息。我也在recv上使用断点,但是客户端无法再执行了,好像它在那里等待。