Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
有什么理由让我得到这样的回答吗;“空白”;当从C客户机向Java服务器读取套接字时?_Java_C_Sockets_Tcp_Bufferedreader - Fatal编程技术网

有什么理由让我得到这样的回答吗;“空白”;当从C客户机向Java服务器读取套接字时?

有什么理由让我得到这样的回答吗;“空白”;当从C客户机向Java服务器读取套接字时?,java,c,sockets,tcp,bufferedreader,Java,C,Sockets,Tcp,Bufferedreader,我正在尝试使用Java服务器和C客户机实现TCP协议。当从客户端读取第一个输入时,代码正常工作。但是,在客户机第二次输入时,服务器读取“ 嗨“或” command1“即使在我尝试使用line=line.replaceAll(“\s”,”)删除空白之后。这些不是空白吗?是否有垃圾从C读入Java?现在,在我发送第二个命令后,程序被阻止,因为服务器无法识别带有这些空格的命令,并且不会将任何内容发送回客户端。非常感谢您的帮助或建议,谢谢您抽出时间 下面是我的Java服务器代码: // A Java p

我正在尝试使用Java服务器和C客户机实现TCP协议。当从客户端读取第一个输入时,代码正常工作。但是,在客户机第二次输入时,服务器读取“ 嗨“或” command1“即使在我尝试使用line=line.replaceAll(“\s”,”)删除空白之后。这些不是空白吗?是否有垃圾从C读入Java?现在,在我发送第二个命令后,程序被阻止,因为服务器无法识别带有这些空格的命令,并且不会将任何内容发送回客户端。非常感谢您的帮助或建议,谢谢您抽出时间

下面是我的Java服务器代码:

// A Java program for a Server 
import java.net.*; 
import java.io.*; 

public class HXServerJava 
{ 
    //initialize socket and input stream 
    private Socket          socket   = null; 
    private ServerSocket    server   = null; 
    private DataInputStream in       =  null; 

    // constructor with port 
    public HXServerJava(int port) 
    { 
        // starts server and waits for a connection 
        try
        { 
            server = new ServerSocket(port); 
            System.out.println("Server started"); 

            System.out.println("Waiting for a client ..."); 

            socket = server.accept(); 
            System.out.println("Client accepted"); 

            // takes input from the client socket 
            BufferedReader in= new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out=new PrintWriter(socket.getOutputStream(),true);
            String line = ""; 

            // reads message from client until "over" is sent 
            while (!line.equals("over")) 
            { 
                try
                { 
                    line = in.readLine(); 
                    System.out.println("line before is: " + line);
                    line = line.replaceAll("\\s",""); //trying to get rid of whitespace
                    System.out.println("line after is: " + line);
                    if ((line != null && line.equals("hi")==true)) {
                        out.print("Welcome by server\n");
                        out.flush();
                        //out.close();
                    }
                    if ((line != null && line.equals("command1")==true)) {
                        out.print("first command executed\n");
                        out.flush();
                        //out.close();
                    }

                } 
                catch(IOException i) 
                { 
                    System.out.println(i); 
                } 
            } 
            System.out.println("Closing connection"); 
            out.print("exit\n");
            out.flush();
            // close connection 
            socket.close(); 
            in.close(); 
            out.close();
        } 
        catch(IOException i) 
        { 
            System.out.println(i); 
        } 
    } 

    public static void main(String args[]) 
    { 
        HXServerJava server = new HXServerJava(5000); 
    } 
} 
#include <netdb.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h> 
#define MAX 80 
#define PORT 5000 
#define SA struct sockaddr 
void func(int sockfd) 
{ 
    char buff[MAX]; 
    int n,m; 
    char *str;
    int exitFlag = 0;
    str = malloc(sizeof (char) * MAX);
    while (exitFlag != 1){
        bzero(buff, sizeof(buff)); 
        printf("Enter the string : "); 
        n = 0; 
        while ((buff[n++] = getchar()) != '\n') 
            ; 
        //strcpy (str, buff);
        //strcat(str, "\n");
        printf("String is: %s\n",buff);
        m = write(sockfd, buff, sizeof(buff)); 
        if (m < 0){
            perror ("ERROR writing to socket\n");
        }
        bzero(buff, sizeof(buff)); 
        m = read(sockfd, buff, sizeof(buff)); 
        if (n < 0) {
            perror("ERROR reading from socket\n");
        }
        printf("From Server : %s\n", buff); 
        if ((strncmp(buff, "exit", 4)) == 0) { 
            exitFlag = 1;
            printf("Client Exit...\n"); 
            break; 
        } 
    } 
} 

int main() 
{ 
    int sockfd, connfd; 
    struct sockaddr_in servaddr, cli; 

    // socket create and varification 
    sockfd = socket(AF_INET, SOCK_STREAM, 0); 
    if (sockfd == -1) { 
        printf("socket creation failed...\n"); 
        exit(0); 
    } 
    else
        printf("Socket successfully created..\n"); 
    bzero(&servaddr, sizeof(servaddr)); 

    // assign IP, PORT 
    servaddr.sin_family = AF_INET; 
    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); 
    servaddr.sin_port = htons(PORT); 

    // connect the client socket to server socket 
    if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0) { 
        printf("connection with the server failed...\n"); 
        exit(0); 
    } 
    else
        printf("connected to the server..\n"); 

    // function for chat 
    func(sockfd); 

    // close the socket 
    close(sockfd); 
} 
下面是我的C客户端代码:

// A Java program for a Server 
import java.net.*; 
import java.io.*; 

public class HXServerJava 
{ 
    //initialize socket and input stream 
    private Socket          socket   = null; 
    private ServerSocket    server   = null; 
    private DataInputStream in       =  null; 

    // constructor with port 
    public HXServerJava(int port) 
    { 
        // starts server and waits for a connection 
        try
        { 
            server = new ServerSocket(port); 
            System.out.println("Server started"); 

            System.out.println("Waiting for a client ..."); 

            socket = server.accept(); 
            System.out.println("Client accepted"); 

            // takes input from the client socket 
            BufferedReader in= new BufferedReader(new InputStreamReader(socket.getInputStream()));
            PrintWriter out=new PrintWriter(socket.getOutputStream(),true);
            String line = ""; 

            // reads message from client until "over" is sent 
            while (!line.equals("over")) 
            { 
                try
                { 
                    line = in.readLine(); 
                    System.out.println("line before is: " + line);
                    line = line.replaceAll("\\s",""); //trying to get rid of whitespace
                    System.out.println("line after is: " + line);
                    if ((line != null && line.equals("hi")==true)) {
                        out.print("Welcome by server\n");
                        out.flush();
                        //out.close();
                    }
                    if ((line != null && line.equals("command1")==true)) {
                        out.print("first command executed\n");
                        out.flush();
                        //out.close();
                    }

                } 
                catch(IOException i) 
                { 
                    System.out.println(i); 
                } 
            } 
            System.out.println("Closing connection"); 
            out.print("exit\n");
            out.flush();
            // close connection 
            socket.close(); 
            in.close(); 
            out.close();
        } 
        catch(IOException i) 
        { 
            System.out.println(i); 
        } 
    } 

    public static void main(String args[]) 
    { 
        HXServerJava server = new HXServerJava(5000); 
    } 
} 
#include <netdb.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h> 
#define MAX 80 
#define PORT 5000 
#define SA struct sockaddr 
void func(int sockfd) 
{ 
    char buff[MAX]; 
    int n,m; 
    char *str;
    int exitFlag = 0;
    str = malloc(sizeof (char) * MAX);
    while (exitFlag != 1){
        bzero(buff, sizeof(buff)); 
        printf("Enter the string : "); 
        n = 0; 
        while ((buff[n++] = getchar()) != '\n') 
            ; 
        //strcpy (str, buff);
        //strcat(str, "\n");
        printf("String is: %s\n",buff);
        m = write(sockfd, buff, sizeof(buff)); 
        if (m < 0){
            perror ("ERROR writing to socket\n");
        }
        bzero(buff, sizeof(buff)); 
        m = read(sockfd, buff, sizeof(buff)); 
        if (n < 0) {
            perror("ERROR reading from socket\n");
        }
        printf("From Server : %s\n", buff); 
        if ((strncmp(buff, "exit", 4)) == 0) { 
            exitFlag = 1;
            printf("Client Exit...\n"); 
            break; 
        } 
    } 
} 

int main() 
{ 
    int sockfd, connfd; 
    struct sockaddr_in servaddr, cli; 

    // socket create and varification 
    sockfd = socket(AF_INET, SOCK_STREAM, 0); 
    if (sockfd == -1) { 
        printf("socket creation failed...\n"); 
        exit(0); 
    } 
    else
        printf("Socket successfully created..\n"); 
    bzero(&servaddr, sizeof(servaddr)); 

    // assign IP, PORT 
    servaddr.sin_family = AF_INET; 
    servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); 
    servaddr.sin_port = htons(PORT); 

    // connect the client socket to server socket 
    if (connect(sockfd, (SA*)&servaddr, sizeof(servaddr)) != 0) { 
        printf("connection with the server failed...\n"); 
        exit(0); 
    } 
    else
        printf("connected to the server..\n"); 

    // function for chat 
    func(sockfd); 

    // close the socket 
    close(sockfd); 
} 
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#定义最大值80
#定义端口5000
#定义SA结构sockaddr
无效函数(int-sockfd)
{ 
字符buff[MAX];
int n,m;
char*str;
int-exitFlag=0;
str=malloc(sizeof(char)*MAX);
while(exitFlag!=1){
bzero(buff,sizeof(buff));
printf(“输入字符串:”);
n=0;
而((buff[n++]=getchar())!='\n')
; 
//strcpy(str,buff);
//strcat(str,“\n”);
printf(“字符串是:%s\n”,buff);
m=写入(sockfd,buff,sizeof(buff));
if(m<0){
perror(“写入套接字时出错\n”);
}
bzero(buff,sizeof(buff));
m=读取(sockfd,buff,sizeof(buff));
if(n<0){
perror(“从套接字读取错误\n”);
}
printf(“来自服务器:%s\n”,buff);
如果((strncmp(buff,“exit”,4))==0{
exitFlag=1;
printf(“客户端退出…\n”);
打破
} 
} 
} 
int main()
{ 
int sockfd,connfd;
servaddr中的struct sockaddru,cli;
//套接字创建和变体
sockfd=套接字(AF_INET,SOCK_STREAM,0);
如果(sockfd==-1){
printf(“套接字创建失败…\n”);
出口(0);
} 
其他的
printf(“套接字已成功创建..\n”);
bzero(&servaddr,sizeof(servaddr));
//分配IP、端口
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=inet_addr(“127.0.0.1”);
servaddr.sinu端口=htons(端口);
//将客户端套接字连接到服务器套接字
如果(connect(sockfd,(SA*)&servaddr,sizeof(servaddr))!=0{
printf(“与服务器的连接失败…\n”);
出口(0);
} 
其他的
printf(“连接到服务器..\n”);
//聊天功能
func(sockfd);
//合上插座
关闭(sockfd);
} 

我不知道C,但似乎它总是发送
sizeof(buff)
字节,这可能比实际读取的字节多(
n
)-也不确定C是否使用与java相同的字符集(默认系统一)谢谢!我还以为我少了点什么呢。就是这样!只发送n个字节而不是sizeof(buff)修复了我的问题。非常感谢。此外,我似乎无法标记为您的评论已解决,但非常感谢您!OT:关于如下语句:
printf(“套接字创建失败…\n”)错误消息应输出到
stderr
,而不是
stdout
。当错误指示来自C库函数时,还应向
stderr
输出系统认为错误发生的文本原因。建议使用
peror()
关于退出(0)
通常,从
main()
返回0表示成功。建议使用:
exit(exit\u失败)@CarlosHeuberger请将您的评论作为答案,以便OP可以标记它。