我用這個代碼從我的Java客戶端發送到我的Java服務器從C客戶端發送一個整數到Java服務器
int n = rand.nextInt(50) + 1;
DataOutputStream dos = new DataOutputStream(_socket.getOutputStream());
dos.writeInt(n);
整數,然後在服務器中使用此代碼閱讀
DataInputStream din = new DataInputStream(socket.getInputStream());
int ClientNumber= din.readInt();
System.out.println(ClientNumber);
ClientNumber++;
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeInt(ClientNumber);
String randomString= getRandomValue(10,20);
dos.writeUTF(randomString);
它完美地工作,但現在我想編寫C客戶端 我想這個代碼
#include <stdio.h>
#include <errno.h>
#include <signal.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define SERVEURNAME "localhost" // adresse IP de mon serveur
int to_server_socket = -1;
void main (void)
{
char *server_name = SERVEURNAME;
struct sockaddr_in serverSockAddr;
struct hostent *serverHostEnt;
long hostAddr;
long status;
char buffer[512];
bzero(&serverSockAddr,sizeof(serverSockAddr));
hostAddr = inet_addr(SERVEURNAME);
if ((long)hostAddr != (long)-1)
bcopy(&hostAddr,&serverSockAddr.sin_addr,sizeof(hostAddr));
else
{
serverHostEnt = gethostbyname(SERVEURNAME);
if (serverHostEnt == NULL)
{
printf("gethost rate\n");
exit(0);
}
bcopy(serverHostEnt->h_addr,&serverSockAddr.sin_addr,serverHostEnt->h_length);
}
serverSockAddr.sin_port = htons(8071);
serverSockAddr.sin_family = AF_INET;
/* creation de la socket */
if ((to_server_socket = socket(AF_INET,SOCK_STREAM,0)) < 0)
{
printf("creation socket client ratee\n");
exit(0);
}
/* requete de connexion */
if(connect(to_server_socket,
(struct sockaddr *)&serverSockAddr,
sizeof(serverSockAddr)) < 0)
{
printf("demande de connection ratee\n");
exit(0);
}
/* envoie de donne et reception */
int value = htons(4);
write(to_server_socket, &value, sizeof(value));
printf(buffer);
}
,但它不工作。我使用Eclipse進行編譯java代碼並運行的C代碼(客戶端),服務器和Xcode的,但我不認爲這個問題是存在的
編輯: 我在服務器上得到一個錯誤
java.net.SocketException異常:在 java.net.SocketOutputStream.socketWrite0(本機方法)在 java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)中斷的管道 在java.net.SocketOutputStream.write (SocketOutputStream.java:115)at java.io.DataOutputStream.writeInt(DataOutputStream.java:182)at ServiceRequest.run( ServiceRequest.java:36)在 java.util.concurrent.Executors $ RunnableAdapter.call(Executors.java:439) 在java.util.concurrent.FutureTask中$ Sync.innerRun(FutureTask.java:303)
我認爲這是因爲我的服務器等待一個整數,但它不是...?
獲取'write'返回的值。如果'-1',然後檢查'errno'。 – austin 2013-05-03 15:24:16
定義「不工作」 – 2013-05-03 15:25:27