Sockets 套接字编程连接错误 我从以下代码中收到错误:`connect failed:connection seeded`。服务器端代码运行正常,但当我运行客户端时,会出现连接失败错误。我正在使用Ubuntu。 服务器端运行:`./server.out 1234`
套接字编程连接错误Sockets 套接字编程连接错误 我从以下代码中收到错误:`connect failed:connection seeded`。服务器端代码运行正常,但当我运行客户端时,会出现连接失败错误。我正在使用Ubuntu。 服务器端运行:`./server.out 1234` ,sockets,tcp,ip,Sockets,Tcp,Ip,套接字编程连接错误 我从以下代码中收到错误:`connect failed:connection seeded`。服务器端代码运行正常,但当我运行客户端时,会出现连接失败错误。我正在使用Ubuntu。 服务器端运行:`./server.out 1234` 客户端运行:`.client.out 127.0.0.1 input.txt 1234` 客户端代码: #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 //#包括“实用的.h” //检查错误 无效错误(字符*错误消息) { pe
我从以下代码中收到错误:`connect failed:connection seeded`。服务器端代码运行正常,但当我运行客户端时,会出现连接失败错误。我正在使用Ubuntu。
服务器端运行:`./server.out 1234`
客户端运行:`.client.out 127.0.0.1 input.txt 1234`
客户端代码:
#包括
#包括
#包括
#包括
#包括
#包括
#包括
#包括
//#包括“实用的.h”
//检查错误
无效错误(字符*错误消息)
{
perror(错误消息);
出口(1);
}
void DieWithUserMessage(const char*msg,const char*detail){
FPUT(味精、标准物质);
FPUT(“:”,标准);
FPUT(详图,标准);
fputc('\n',stderr);
出口(1);
}
void DieWithSystemMessage(const char*msg){
佩罗尔(味精);
出口(1);
}
//定义缓冲区大小
枚举大小常量{
MAXSTRINGLENGTH=128,
BUFSIZE=512,
};
int main(int argc,char*argv[]){
字符缓冲区[BUFSIZE];
//FILE*fp,*fpOut;//声明文件指针
if(argc<3 | | argc>4)//测试参数的正确数量
DieWithUserMessage(“参数)”,“[]”;
char*servIP=argv[1];//第一个arg:服务器IP地址(虚线四元)
char*echoString=argv[2];//第二个arg:要回显的字符串
//第三个参数(可选):服务器端口(数字)。7是众所周知的回显端口
在服务端口=(argc==4)中,atoi(argv[3]):7;
//使用TCP创建可靠的流套接字
int sock=socket(AF_INET、sock流、IPPROTO_TCP);
if(sock<0)
DieWithSystemMessage(“套接字()失败”);
//构造服务器地址结构
servAddr中的struct sockaddr\u;//服务器地址
memset(&servAddr,0,sizeof(servAddr));//零出结构
servAddr.sin_family=AF_INET;//IPv4地址族
//转换地址
int rtnVal=inet\u pton(AF\u inet、servIP和servAddr.sin\u addr.s\u addr);
如果(rtnVal==0)
DieWithUserMessage(“inet_pton()失败”,“地址字符串无效”);
否则如果(rtnVal<0)
DieWithSystemMessage(“inet_pton()失败”);
servAddr.sin_port=htons(servPort);//服务器端口
//建立与echo服务器的连接
if(connect(sock,(struct sockaddr*)&servAddr,sizeof(servAddr))<0
DieWithSystemMessage(“连接()失败”);
/*
//开始从计算机读取文件输入
char-buf[1000];
fp=fopen(“input.txt”,“r”);//打开文件
如果(!fp){
printf(“它失败了!\n”);
返回1;
}
while(fgets(buf,1000,fp)!=NULL){//获取buf char数组中的文件输入值
//printf(“program.txt文件中的输入值:%s”,buf);
printf(“从服务器收到的消息:”);
*/
size_t echoStringLen=strlen(echoString);//确定输入长度
//将字符串发送到服务器
ssize_t numBytes=send(sock,echoString,echoStringLen,0);
如果(单位<0)
DieWithSystemMessage(“发送()失败”);
else if(numBytes!=echoStringLen)
DieWithUserMessage(“send(),“发送了意外的字节数”);
//从服务器接收相同的字符串
unsigned int totalBytesRcvd=0;//接收的总字节数
//设置以打印回显字符串
而(totalBytesRcvdI received the error: `connect failed: connection refused` from the following code. Server side code runs fine, but when I run the client side I get the connect failed error. I am using Ubuntu.
server side run: `./server.out 1234`
client side run: `.client.out 127.0.0.1 input.txt 1234`
Client code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
//#include "Practical.h"
// check error
void DieWithError(char *errorMessage)
{
perror(errorMessage);
exit(1);
}
void DieWithUserMessage(const char *msg, const char *detail) {
fputs(msg, stderr);
fputs(": ", stderr);
fputs(detail, stderr);
fputc('\n', stderr);
exit(1);
}
void DieWithSystemMessage(const char *msg) {
perror(msg);
exit(1);
}
//define buffer size
enum sizeConstants {
MAXSTRINGLENGTH = 128,
BUFSIZE = 512,
};
int main(int argc, char *argv[]) {
char buffer[BUFSIZE];
//FILE *fp,*fpOut; // declare file pointer
if (argc < 3 || argc > 4) // Test for correct number of arguments
DieWithUserMessage("Parameter(s)","<Server Address> <Echo Word> [<Server Port>]");
char *servIP = argv[1]; // First arg: server IP address (dotted quad)
char *echoString = argv[2]; // Second arg: string to echo
// Third arg (optional): server port (numeric). 7 is well-known echo port
in_port_t servPort = (argc == 4) ? atoi(argv[3]) : 7;
// Create a reliable, stream socket using TCP
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock < 0)
DieWithSystemMessage("socket() failed");
// Construct the server address structure
struct sockaddr_in servAddr; // Server address
memset(&servAddr, 0, sizeof(servAddr)); // Zero out structure
servAddr.sin_family = AF_INET; // IPv4 address family
// Convert address
int rtnVal = inet_pton(AF_INET, servIP, &servAddr.sin_addr.s_addr);
if (rtnVal == 0)
DieWithUserMessage("inet_pton() failed", "invalid address string");
else if (rtnVal < 0)
DieWithSystemMessage("inet_pton() failed");
servAddr.sin_port = htons(servPort); // Server port
// Establish the connection to the echo server
if (connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0)
DieWithSystemMessage("connect() failed");
/*
//start reading file input from computer
char buf[1000];
fp =fopen("input.txt","r");//open the file
if (!fp){
printf("it failed!\n");
return 1;
}
while(fgets (buf, 1000, fp)!=NULL) { // take the file input value in buf char array
//printf("The input value in program.txt file: %s",buf);
printf("Received Message from server: ");
*/
size_t echoStringLen = strlen(echoString); // Determine input length
// Send the string to the server
ssize_t numBytes = send(sock, echoString, echoStringLen, 0);
if (numBytes < 0)
DieWithSystemMessage("send() failed");
else if (numBytes != echoStringLen)
DieWithUserMessage("send()", "sent unexpected number of bytes");
// Receive the same string back from the server
unsigned int totalBytesRcvd = 0; // Count of total bytes received
// Setup to print the echoed string
while (totalBytesRcvd < echoStringLen) {
// I/O buffer
/* Receive up to the buffer size (minus 1 to leave space for
a null terminator) bytes from the sender */
numBytes = recv(sock, buffer, BUFSIZE - 1, 0);
if (numBytes < 0)
DieWithSystemMessage("recv() failed");
else if (numBytes == 0)
DieWithUserMessage("recv()", "connection closed prematurely");
totalBytesRcvd += numBytes; // Keep tally of total bytes
buffer[numBytes] = '\0'; // Terminate the string!
printf("%s",buffer);
//fputs(buffer, stdout); // Print the echo buffer
}
//fpOut = fopen("gcd.txt","w"); // open the gcd txt file in write mode
//fprintf(fpOut,"%s",buffer );// write the gcd value in gcd text file
//fputc('\n', stdout);
//fclose(fpOut);
//fclose(fp);
return 0;
close(sock);
exit(0);
}
Server code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
//#include "Practical.h"
void DieWithError(char *errorMessage)
{
perror(errorMessage);
exit(1);
}
void DieWithUserMessage(const char *msg, const char *detail) {
fputs(msg, stderr);
fputs(": ", stderr);
fputs(detail, stderr);
fputc('\n', stderr);
exit(1);
}
void DieWithSystemMessage(const char *msg) {
perror(msg);
exit(1);
}
static const int MAXPENDING = 5; // Maximum outstanding connection requests
int main(int argc, char *argv[]) {
if (argc != 2) // Test for correct number of arguments
DieWithUserMessage("Parameter(s)", "<Server Port>");
in_port_t servPort = atoi(argv[1]); // First arg: local port
// Create socket for incoming connections
int servSock; // Socket descriptor for server
if ((servSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
DieWithSystemMessage("socket() failed");
// Construct local address structure
struct sockaddr_in servAddr; // Local address
memset(&servAddr, 0, sizeof(servAddr)); // Zero out structure
servAddr.sin_family = AF_INET; // IPv4 address family
servAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Any incoming interface
servAddr.sin_port = htons(servPort); // Local port
// Bind to the local address
if (bind(servSock, (struct sockaddr*) &servAddr, sizeof(servAddr)) < 0)
DieWithSystemMessage("bind() failed");
// Mark the socket so it will listen for incoming connections
if (listen(servSock, MAXPENDING) < 0)
DieWithSystemMessage("listen() failed");
for (;;) { // Run forever
struct sockaddr_in clntAddr; // Client address
// Set length of client address structure (in-out parameter)
socklen_t clntAddrLen = sizeof(clntAddr);
printf("\nIam here\n");
// Wait for a client to connect
int clntSock = accept(servSock, (struct sockaddr *) &clntAddr, &clntAddrLen);
if (clntSock < 0)
DieWithSystemMessage("accept() failed");
// clntSock is connected to a client!
char clntName[INET_ADDRSTRLEN]; // String to contain client address
if (inet_ntop(AF_INET, &clntAddr.sin_addr.s_addr, clntName,sizeof(clntName)) != NULL)
printf("Got response from client: %s/%d\n", clntName, ntohs(clntAddr.sin_port));
else
puts("Unable to get client address");
HandleTCPClient(clntSock);
}
// NOT REACHED
}
void HandleTCPClient(int clntSocket) {
FILE *fp;
char echoBuffer[RCVBUFSIZE]; /* Buffer for echo string */
int recvMsgSize; /* Size of received message */
/* Receive message from client */
if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0)
DieWithError("recv() failed");
printf("Server asked file name from Client side:: %s", echoBuffer);
fp =fopen("echoBuffer","r");//open the file
if (!fp){
printf("it failed!\n");
//return 1;
}
//int i,j;
//sscanf(echoBuffer, "%d %d", &i,&j);// take the two number from client and convert string to integer.
//sprintf(echoBuffer,"%d",gcd(i,j)); // call the gcd method.
/* Send received string and receive again until end of transmission */
while (recvMsgSize > 0){ /* zero indicates end of transmission */
/* Echo message back to client */
if (send(clntSocket, echoBuffer, recvMsgSize, 0) != recvMsgSize)
DieWithError("send() failed");
/* See if there is more data to receive */
if ((recvMsgSize = recv(clntSocket, echoBuffer, RCVBUFSIZE, 0)) < 0)
DieWithError("recv() failed");
}
fclose(fp);
close(clntSocket); /* Close client socket */
}
in_port_t servPort = (argc ==4) ? atoi(argv[3]) : 7;