通信c服务器和java客户端时出错
我正在尝试制作一个小的tcp echo服务器,它用C语言支持多线程,用java编写一个客户端,两者都使用套接字进行通信。通信开始得很好,但不知何故,服务器和客户端之间传递的字符串在几次尝试(添加新行字符或发送的旧消息片段)后开始“损坏”。 我搜索了论坛,认为问题在于C的空字符,但在java中删除它没有任何区别。 以下是C服务器的代码:通信c服务器和java客户端时出错,java,c,sockets,tcp,Java,C,Sockets,Tcp,我正在尝试制作一个小的tcp echo服务器,它用C语言支持多线程,用java编写一个客户端,两者都使用套接字进行通信。通信开始得很好,但不知何故,服务器和客户端之间传递的字符串在几次尝试(添加新行字符或发送的旧消息片段)后开始“损坏”。 我搜索了论坛,认为问题在于C的空字符,但在java中删除它没有任何区别。 以下是C服务器的代码: #include <stdio.h> #include <stdlib.h> #include <string.h> #inc
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <linux/limits.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <errno.h>
#include <netinet/in.h>
#include <time.h>
#include <stdlib.h>
#include <limits.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <pthread.h>
struct message {
int operacion;
int dato;
};
int max_attempts;
int obtenerMaxAttempts() {
FILE *fp;
fp = fopen("server.conf", "r");
if (fp == NULL) {
perror("Error abriendo fichero");
printf("Errno:%d", errno);
}
char line[LINE_MAX];
char *aux;
while (fgets(line, LINE_MAX, fp) != NULL) {
aux = strtok(line, " ");
if (strcmp(aux, "maxAttempts") == 0) {
aux = strtok(NULL, " ");
max_attempts = atoi(aux);
}
}
return (max_attempts);
}
int obtenerPuerto() {
in_port_t puerto;
FILE *fp;
fp = fopen("server.conf", "r");
if (fp == NULL) {
perror("Error abriendo fichero");
printf("Errno:%d", errno);
}
char line[LINE_MAX];
char *aux;
while (fgets(line, LINE_MAX, fp) != NULL) {
aux = strtok(line, " ");
if (strcmp(aux, "port") == 0) {
aux = strtok(NULL, " ");
puerto = atoi(aux);
}
}
return (puerto);
}
void *eco(void *new_sockfd) {
int socket = *((int *) new_sockfd);
free(new_sockfd);
int longitud;
char *mensaje_recv, *mensaje_env;
mensaje_recv = malloc(100 * sizeof (char));
mensaje_env=malloc(100 * sizeof (char));
while (1) {
longitud = recv(socket, (void *) mensaje_recv, 100, 0);
printf("Mensaje recibido del cliente: %s", mensaje_recv);
strcpy(mensaje_env,mensaje_recv);
printf("Mensaje enviado al cliente: %s", mensaje_env);
send(socket, (void *) mensaje_env, sizeof (mensaje_env), 0);
/* Cerrar el socket */
}
}
/* Función principal del servidor */
int main(int argc, char *argv[]) {
pthread_t idHilo;
int error;
struct sockaddr_in entrada;
entrada.sin_family = AF_INET;
entrada.sin_addr.s_addr = htonl(INADDR_ANY);
entrada.sin_port = htons(obtenerPuerto());
/* Comprueba que servidorTCP tiene 1 argumento (servidorTCP)*/
if (argc != 1) {
printf("Número de parámetros inválido.\n Sintaxis: servidorTCP \n");
exit(EXIT_FAILURE);
}
/* Creación del socket TCP */
int socketid = socket(AF_INET, SOCK_STREAM, 0); // SOCK_STREAM(conexión tcp, mirar documentación de socket())
if (socketid == -1) {
perror("Error creando el socket");
printf("Errno=%d\n", errno);
exit(EXIT_FAILURE);
}
/************************************************************************************/
/* Preparar un nombre local en el puerto especificado: El nombre local
*/
/* se prepara con la propia dirección de Internet que la sabe el sistema,
*/
/* y el puerto se obtiene del parámetro recibido
*/
/************************************************************************************/
/* Asigna nombre local al socket: Asignación de una dirección local
*/
if (bind(socketid, (struct sockaddr*) &entrada, sizeof (entrada)) == -1) {
perror("Error asignando nombre de socket");
printf("Errno=%d\n", errno);
exit(EXIT_FAILURE);
}
int new_sockfd;
#define max_queue 10
/* Esperar el establecimiento de alguna conexión */
if (listen(socketid, max_queue) == -1) {
perror("Error habilitando socket para conexiones");
printf("Errno=%d\n", errno);
exit(EXIT_FAILURE);
}
struct sockaddr_in remote_addr;
int addrlen;
addrlen = sizeof (struct sockaddr_in);
while (1) {
new_sockfd = accept(socketid, (struct sockaddr *) &remote_addr, &addrlen);
if (new_sockfd == -1) {
perror("Error aceptando la conexión");
printf("Errno=%d\n", errno);
exit(EXIT_FAILURE);
}
int *numero = malloc(sizeof (int));
*numero = new_sockfd;
//error = pthread_create(&idHilo, NULL, juego, (void *) numero);
error = pthread_create(&idHilo, NULL, eco, (void *) numero);
if (error != 0) {
perror("No puedo crear thread");
exit(EXIT_FAILURE);
}
}
/* Recibir el mensaje */
}
#包括
#包括
#包括
#包括
#包括/*见附注*/
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
结构消息{
内部操作;
国际达托;
};
int max_尝试次数;
int obtenerMaxAttempts(){
文件*fp;
fp=fopen(“server.conf”,“r”);
如果(fp==NULL){
perror(“错误abriendo fichero”);
printf(“错误号:%d”,错误号);
}
字符行[line_MAX];
char*aux;
while(fgets(行,行最大值,fp)!=NULL){
aux=strtok(第“”行);
如果(strcmp(辅助,“最大尝试”)==0){
aux=strtok(空,“”);
最大尝试次数=atoi(辅助);
}
}
返回(最大尝试次数);
}
int obtenerPuerto(){
在港口港;
文件*fp;
fp=fopen(“server.conf”,“r”);
如果(fp==NULL){
perror(“错误abriendo fichero”);
printf(“错误号:%d”,错误号);
}
字符行[line_MAX];
char*aux;
while(fgets(行,行最大值,fp)!=NULL){
aux=strtok(第“”行);
如果(strcmp(辅助,“端口”)==0){
aux=strtok(空,“”);
波多黎各=阿托伊(辅);
}
}
返回(波多黎各);
}
void*eco(void*new\u sockfd){
int socket=*((int*)新的_sockfd);
免费的(新的);
内长;
char*mensaje_recv,*mensaje_env;
mensaje_recv=malloc(100*sizeof(char));
mensaje_env=malloc(100*sizeof(char));
而(1){
longitud=recv(插座,(空心*)门萨杰鲁recv,100,0);
printf(“客户的接受程度:%s”,接受程度);
strcpy(mensaje_env,mensaje_recv);
printf(“Mensaje envado al client:%s”,Mensaje_env);
send(socket,(void*)mensaje_env,sizeof(mensaje_env),0;
/*塞拉尔插座*/
}
}
/*施维多尔校长职能*/
int main(int argc,char*argv[]){
pthread_t idHilo;
整数误差;
entrada中的结构sockaddr_;
entrada.sin_family=AF_INET;
entrada.sin_addr.s_addr=htonl(INADDR_ANY);
entrada.sin_port=htons(obtenerporto());
/*一个论证(servidorTCP)的综合服务*/
如果(argc!=1){
PrtTf(“n席Melo de PaulaMethsViaLado.\n SnTraceS:ServordRTCP \n”);
退出(退出失败);
}
/*Creación del socket TCP*/
int socketid=socket(AF_INET,SOCK_STREAM,0);//SOCK_STREAM(conexión tcp,mirar documentación de socket())
if(socketid==-1){
perror(“错误creando el套接字”);
printf(“Errno=%d\n”,Errno);
退出(退出失败);
}
/************************************************************************************/
/*准备在波多黎各特别行政区的当地名称:当地名称
*/
/*在互联网系统的准备工作中,
*/
帕尔塔地铁
*/
/************************************************************************************/
/*Asigna nombre local al socket:Asignación de una dirección local
*/
if(bind(socketid,(struct sockaddr*)和entrada,sizeof(entrada))=-1){
perror(“错误asignando nombre de socket”);
printf(“Errno=%d\n”,Errno);
退出(退出失败);
}
int new_sockfd;
#定义最大队列10
/*埃斯佩拉尔·艾尔古纳·科内西翁庄园酒店*/
if(侦听(socketid,max_queue)=-1){
perror(“错误适应能力”和“错误适应能力”);
printf(“Errno=%d\n”,Errno);
退出(退出失败);
}
远程地址中的结构sockaddr\u;
int addrlen;
addrlen=sizeof(结构sockaddr_in);
而(1){
new_sockfd=accept(socketid,(struct sockaddr*)和remote_addr,&addrlen);
如果(新的_sockfd==-1){
perror(“aceptando la conexión错误”);
printf(“Errno=%d\n”,Errno);
退出(退出失败);
}
int*numero=malloc(sizeof(int));
*numero=新的\u sockfd;
//error=pthread_create(&idHilo,NULL,juego,(void*)numero);
error=pthread_create(&idHilo,NULL,eco,(void*)numero);
如果(错误!=0){
perror(“无puedo crear螺纹”);
退出(退出失败);
}
}
/*雷西比尔·门萨耶酒店*/
}
下面是java客户端的代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.*;
/**
*
* @author obok
*/
public class clienteTCP {
public static void main(String[] args) throws IOException {
/**
* Comprobamos el número de parámetros
*
*/
System.out.println(args);
System.out.println(args.length);
if (args.length != 2) {
System.out.println("Número de parámetros inválido");
System.out.println("Sintaxis: clienteTCP <dirección> <puerto>");
return;
}
int puerto;
puerto = Integer.parseInt(args[1]);
InetAddress direccion = null;
try {
direccion = InetAddress.getByName(args[0]);
} catch (UnknownHostException ex) {
//Logger.getLogger(clienteTCP.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("La dirección no es correcta.");
}
Socket socket = null;
System.out.println("Dirección:" + direccion + " Puerto: " + puerto);
try {
socket = new Socket(direccion, puerto);
} catch (IOException ex) {
System.out.println("Error de entrada salida creando el socket.");
return;
//Logger.getLogger(clienteTCP.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedReader in;
String mensaje;
mensaje = "";
String mensaje2;
in = new BufferedReader(new InputStreamReader(System.in));
//DataOutputStream outToServer = new DataOutputStream(socket.getOutputStream());
PrintWriter outToServer = new PrintWriter(socket.getOutputStream(),true);
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
while (!mensaje.equalsIgnoreCase("salir")) {
System.out.println("Introduzca mensaje: ");
mensaje = in.readLine();
System.out.println("Mensaje enviado al servidor: "+mensaje);
outToServer.println(mensaje);
//outToServer.writeBytes(mensaje+"\n");
mensaje2 = inFromServer.readLine();
mensaje2= mensaje2.replaceAll("/0", "");
System.out.println("Mensaje recibido del servidor: "+ mensaje2);
}
socket.close();
}
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.io.PrintWriter;
导入java.net。*;
/**
*
*@作者奥博克
*/
公共类客户{
公共静态void main(字符串[]args)引发IOException{
/**
*康普拉莫斯
*
*/
系统输出打印项次(args);
系统输出打印项次(参数长度);
如果(参数长度!=2){
系统。
System.out.println(“Sintaxis:clientTCP”);
返回;
}
国际波多黎各;
puerto=Integer.parseInt(args[1]);
InetAddress direccion=null;
试一试{
direccion=InetAddress.getByName(args[0]);
}捕获(未知后异常除外){
//Logger.getLogger(clientTCP.class.getName()).log(Level.SEVERE,null,ex);
System.out.println(“La dirección no es correcta.”);
}
套接字=空;
System.out.println(“Dirección:+direccion+”Puerto:+Puerto”);
试一试{
所以
//Simple echo server
ServerSocket welcomeSocket = new ServerSocket(//your port);
Socket connectionSocket = welcomeSocket.accept();
System.out.println("Connection successful");
mensaje = in.readLine();
DataInputStream