java的客户端可以连接CPlus的服务端

  今天做的实验,用c++做的服务端,端口号为6000;用java做的客户端,IP为127.0.0.1,port为6000,结果双方可以连接上线;

贴代码:

服务端:

#include <winsock2.h>
#include <iostream>
using namespace std;
SOCKET sockConn = NULL;
char content[100] = " ";
int flag = 1;
DWORD WINAPI MYrevc(LPVOID lp)
{
while(1)
{
char recvBuf[100];
if(flag==0)
{

recv(sockConn,recvBuf,100,0);///////////
}
if(recvBuf[0]!=0)
{
cout<<recvBuf<<endl;
//cout<<"MYrecv"<<endl;
flag = 1;
}
Sleep(1000);
}
return 0;
}
DWORD WINAPI MYsend(LPVOID lp)
{
cin>>content;
send(sockConn,content,strlen(content)+1,0);
flag = 0;
return 0;
}
int main()
{
WORD wVersionRequested;
WSADATA wsaData;
int err;

wVersionRequested = MAKEWORD( 1, 1 );

err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
{
return 0;
}

if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 )
{
WSACleanup( );
return 0;
}
SOCKET sockSrv=socket(AF_INET,SOCK_STREAM,0);

SOCKADDR_IN addrSrv;
addrSrv.sin_addr.S_un.S_addr=htonl(INADDR_ANY);
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);

bind(sockSrv,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));

listen(sockSrv,5);

SOCKADDR_IN addrClient;
int len=sizeof(SOCKADDR);
sockConn=accept(sockSrv,(SOCKADDR*)&addrClient,&len);
cout<<"client has logined!"<<endl;
MYsend(NULL);
HANDLE rThread = CreateThread(NULL,0,MYrevc,NULL,0,NULL);//接收消息的线程
CloseHandle(rThread);
while(1)
{
if(flag)
{
HANDLE sThread = CreateThread(NULL,0,MYsend,NULL,0,NULL);
CloseHandle(sThread);
}
Sleep(1000);
}
// closesocket(sockConn);
return 1;
}

 

客户端:

package sock;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class Sock {
public static void main(String[] args) {
try {
Socket sock = new Socket("127.0.0.1",6000);
System.out.println("Connect Successed!");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

 

运行效果:

 

服务端:

客户端:

 

 

 

 

posted @ 2015-08-20 11:55  构建巨人肩膀  阅读(197)  评论(0编辑  收藏  举报