zoukankan      html  css  js  c++  java
  • 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();
    }
    }
    }

    运行效果:

    服务端:

    客户端:

  • 相关阅读:
    swagger配置
    windows下安装redis
    Redis在windows下安装过程
    jenkins安装部署全过程
    MySQL表名不区分大小写的设置方法
    Linux常用命令
    java 执行redis的部分方法
    把jar包加入本地maven库内
    Java 枚举7常见种用法
    【转】每天一个linux命令(1):ls命令
  • 原文地址:https://www.cnblogs.com/yuan951/p/4744731.html
Copyright © 2011-2022 走看看