使用套接字在服务器(ANSI C)和客户端(JAVA)之间进行通信

时间:2013-06-27 09:09:27

标签: java c sockets client-server communication

好的,我有一个问题。我有一个用Java编写的小项目(游戏)(客户端 - 服务器)。一切正常。但我想重写服务器到ANSI C.我启动服务器,它等待客户端的连接。当我启动客户端时,建立连接。到目前为止一切正常。但是,当我尝试从服务器 - 服务器发送向客户端发送内容时,但客户端不接收它。有什么想法吗?

服务器来源:

#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <winsock2.h>

DWORD WINAPI receive_cmds(LPVOID *lpParam) {
SOCKET *players = (SOCKET *) lpParam;
SOCKET player1 = (SOCKET)players[0];
SOCKET player2 = (SOCKET)players[1];
char recvBuff[100];
char sndBuff[100];
int nReadBytes;
int turn = 1;
int res;

printf("Utworzono nowy pokoj.\r\n");

strcpy(sndBuff,"PLAYER1");
printf("%s\n",sndBuff);
if((res = send(player1,sndBuff,sizeof(sndBuff),0)) == 0) {
    printf("Gracz 1 rozlaczony.\n");
    closesocket(player1);
    closesocket(player2);
    printf("Zamykam pokoj.\n");
    ExitThread(0);
}
strcpy(sndBuff,"TURN1");
printf("%s\n",sndBuff);
if((res = send(player1,sndBuff,sizeof(sndBuff),0)) == 0) {
    printf("Gracz 1 rozlaczony.\n");
    closesocket(player1);
    closesocket(player2);
    printf("Zamykam pokoj.\n");
    ExitThread(0);
}
strcpy(sndBuff,"PLAYER2");
printf("%s\n",sndBuff);
if((res = send(player2,sndBuff,sizeof(sndBuff),0)) == 0) {
    printf("Gracz 2 rozlaczony.\n");
    closesocket(player1);
    closesocket(player2);
    printf("Zamykam pokoj.\n");
    ExitThread(0);
}
strcpy(sndBuff,"TURN0");
printf("%s\n",sndBuff);
if((res = send(player2,sndBuff,sizeof(sndBuff),0)) == 0) {
    printf("Gracz 2 rozlaczony.\n");
    closesocket(player1);
    closesocket(player2);
    printf("Zamykam pokoj.\n");
    ExitThread(0);
}

while(TRUE) {
    if(turn == 1) {
        nReadBytes = recv(player1, recvBuff, sizeof(recvBuff), 0);
        if(nReadBytes == 0) {
            printf("Gracz 1 rozlaczony.\n");
            closesocket(player1);
            closesocket(player2);
            printf("Zamykam pokoj.\n");
            ExitThread(0);
        } else {
            printf("Odczytalem dane od gracza 1.\n");
            printf("%s\n",recvBuff);
        }
    }
}
}

int main(void) {
DWORD thread;
WSADATA wsaData;
SOCKET sock;
SOCKET players[2];
struct sockaddr_in from;
struct sockaddr_in server;
int ret;
int fromlen;

printf("Serwer oczekuje na polaczenia.\r\n");

if((ret = WSAStartup(0x101,&wsaData)) != 0) {
    return 0;
}

server.sin_family=AF_INET;
server.sin_addr.s_addr=INADDR_ANY;
server.sin_port=htons(5000);

if((sock=socket(AF_INET,SOCK_STREAM,0)) == INVALID_SOCKET) {
    return 0;
}

if(bind(sock,(struct sockaddr*)&server,sizeof(server)) != 0) {
    return 0;
}

if(listen(sock,5) != 0) {
    return 0;
}

fromlen = sizeof(from);

while(TRUE) {
    players[0] = accept(sock,(struct sockaddr*)&from,&fromlen);
    printf("Gracz 1 polaczony\r\n");
    players[1] = accept(sock,(struct sockaddr*)&from,&fromlen);
    printf("Gracz 2 polaczony\r\n");
    CreateThread(NULL, 0,receive_cmds,(LPVOID)players, 0, &thread);
}

closesocket(sock);
WSACleanup();

return 0;
}

comunicate的客户端类:

package game;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class Connection extends Thread{
private static final int PORT = 5000;
private static InetAddress IP;
private static Socket socket = null;
private BufferedReader in;
private PrintWriter out;
private Game game;

public Connection(Game game){
this.game = game;
try {
    IP = InetAddress.getByName(game.getAddr());
    socket = new Socket(IP,PORT);
    out = new PrintWriter(socket.getOutputStream(), true);
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (Exception e) {
    e.printStackTrace();
}
}

public void initGame() {
String message;
System.out.println("Polaczono.");
message = rcv();
System.out.println(message);
if((message.contains("PLAYER1")) == true) {
    Game.player = 1;
} else if((message.contains("PLAYER2")) == true) {
    Game.player = 2;
}
message = rcv();
System.out.println(message);
if((message.contains("TURN1")) == true) {
    Game.turn = true;
} else if((message.contains("TURN0")) == true) {
    Game.turn = false;
}
}

public void listen() {
if(Game.turn == false) {
    String message = rcv();
    System.out.println("Msg rcv: " + message);
    if(message.contains("CREATE")) {
    System.out.println("CREATE");
    Game.unitList.add(new Unit(
        Integer.parseInt(message.substring(6,8)),
        Integer.parseInt(message.substring(8,10)),
        Integer.parseInt(message.substring(10,12)),
        Integer.parseInt(message.substring(12,14))));
    for(Unit u : Game.unitList) {
        u.writeUnit();
    }
    }
    if(message.contains("DELETE")) {
    System.out.println("DELETE");
    for(Unit u : Game.unitList) {
        u.writeUnit();
    }
    for(Unit u : Game.unitList) {
        if(u.getX() == Integer.parseInt(message.substring(6,8))
        && u.getY() == Integer.parseInt(message.substring(8,10))) {
        Game.unitList.remove(u);
        }
    }
    System.out.println("Po usunieciu:");
    for(Unit u : Game.unitList) {
        u.writeUnit();
    }
    }
    if(message.contains("MOVE")) {
    System.out.println("MOVE");
    for(Unit u : Game.unitList) {
        u.writeUnit();
    }
    for(Unit u : Game.unitList) {
        if(u.getX() == Integer.parseInt(message.substring(4,6))
        && u.getY() == Integer.parseInt(message.substring(6,8))) {
        System.out.println("Znalazlem jednostke do przesuniecia");
        u.setX(Integer.parseInt(message.substring(8,10)));
        u.setY(Integer.parseInt(message.substring(10,12)));
        }
    }
    }
    if(message.contains("OCCUPY")) {
    System.out.println("OCCUPY");
    for(Building u : Game.buildingList) {
        if(u.getX() == Integer.parseInt(message.substring(4,6))
        && u.getY() == Integer.parseInt(message.substring(6,8))) {
        u.setOwner(Integer.parseInt(message.substring(8,10)));
        u.setSS();
        }
    }
    }
    if(message.contains("LOSE")) {
    System.out.println("LOSE");
    LoseWindow loseWindow = new LoseWindow();
    }
    if(message.contains("TURN1")){
    Game.turn = true;
    }
}
}

public void snd(String s) {
out.println(s);
}

public String rcv() {
String message = null;
try {
    message = in.readLine();
} catch (Exception e) {
    e.printStackTrace();
}
return message;
}

public void closeConnection() {
try {
    socket.close();
    System.out.println("Zakonczono polaczenie.");
} catch (IOException e) {
    e.printStackTrace();
}
}

public Socket getSocket() {
return socket;
}
}

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

问题似乎是您尝试确定要发送的字节数的方式:sizeof(sndBuff[100])。由于sndBuff是char [100],sizeof(sndBuff[..])是单个char的大小。所以你总是只发送一个字节(更多,100甚至不是一个有效的索引)。只需使用strlen(sndBuff)来确定要发送的字节数。

修改 第二点是,您的客户端会读取未发送的in.readLine(),但您不会发送任何换行符。尝试添加它们。

答案 1 :(得分:1)

在java客户端,你使用readline函数读取socket,它将在输出之前等待,直到换行或socket关闭。我建议你追加&#39; \ n&#39;在您从服务器发送的消息中。