我使用此代码将整数从我的 Java 客户端发送到我的 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.socketWrite(SocketOutputStream.java:92) 在 java.net.SocketOutputStream.write(SocketOutputStream.java:115) 的 java.net.SocketOutputStream.socketWrite0(Native Method) 的管道损坏在 java.io.DataOutputStream.writeInt(DataOutputStream.java:182) 在 ServiceRequest.run(ServiceRequest.java:36) 在 java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:439) 在 java.util。 concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
我认为这是因为我的服务器等待一个整数,但它不是......?