8
我想通過套接字通信一個Java客戶端和一個C服務器 所有似乎工作正常,如果我嘗試服務器在命令行上使用nc連接或如果我使用nc作爲服務器並連接到我的Java客戶端,但是當我嘗試連接Java Client和C服務器時,它不起作用。套接字通信,Java客戶端C服務器
客戶端啓動連接,併發送消息,消息被服務器接收,但服務器的響應永遠不會到達客戶端。
服務器代碼:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int sockfd, clisockfd, portno;
char * start = "hello";
char * end = "bye";
socklen_t clilen;
char buffer[256];
char contentBuffer[255];
struct sockaddr_in serv_addr, cli_addr;
int n;
//int optval;
/* First call to socket() function */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
perror("ERROR opening socket");
return(1);
}
/* Initialize socket structure */
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = 5000;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
{
perror("ERROR on binding");
return(1);
}
listen(sockfd,5);
clilen = (socklen_t) sizeof(cli_addr);
clisockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen);
if (clisockfd < 0)
{
perror("ERROR on accept");
return(1);
}
while (strcmp(end, contentBuffer) !=0)
{
bzero(buffer,256);
bzero(contentBuffer,255);
/* If connection is established then start communicating */
n = read(clisockfd,buffer,255);
if (n < 0)
{
perror("ERROR reading from socket");
return(1);
}
strncpy(contentBuffer,buffer,strlen(buffer) - 1);
if (strcmp(start, contentBuffer) ==0)
{
printf("command: %s\n",buffer);
n = write(clisockfd,"Roger that",11);
if (n < 0)
{
perror("ERROR writing to socket");
return(1);
}
}
else
{
printf("Unknown command: %s\n",buffer);
n = write(clisockfd,"ERRCmd",7);
if (n < 0)
{
perror("ERROR writing to socket");
return(1);
}
}
}
close(sockfd);
return 0;
}
客戶端代碼:
import java.io.*;
import java.net.*;
public class Cliente {
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println(
"Usage: java EchoClient <host name> <port number>");
System.exit(1);
}
String hostName = args[0];
int portNumber = Integer.parseInt(args[1]);
Socket firstSocket = new Socket(hostName, portNumber);
PrintWriter out = new PrintWriter(firstSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(firstSocket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
System.out.println("received: " + in.readLine());
}
in.close();
stdIn.close();
firstSocket.close();
}
}
謝謝loooot!這是問題:D – Jebe
@Jebe如果答案給你正確的方向來解決問題,你應該接受答案 – rkosegi