请问用C语言 socket编程,如何使TCP客户端实现网络恢复后自动重连的功能?
呵呵,想了想 大概是这样几种可能,你可以尝试一下。 1。重新连接的过程要重新创建sockclient也就是重新调用函数创建。2。服务器关闭后再开启,绑定的是同一个接口。当关闭后再开启的时间较短时端口可能处于忙状态,倒置再开启绑定到该端口失败,也就是服务器端启动失败。 处理办法:你可以利用setsockopt函数,将端口设置为可重用状态,我忘记那个宏是什么了你可以上网去查查setsockopt的用法。希望对你有用 best wishes
建议你去我的空间博客中看一下关于socket连接过程,你会明白为什么连接不了,因为accept后返回的socket是系统随机分配的。TCP指的点对点,其实就是socket对socket。

采用tcp协议,使用socket编程,编写程序完成客户端发送消息给服务端,服务端接到消息后,再发
服务端代码: /*server.c*/#include #include #include #include #include #include #include #include #define PORT4321#define BUFFER_SIZE 1024#define MAX_QUE_CONN_NM 5int main(){struct sockaddr_in server_sockaddr, client_sockaddr;int sin_size, recvbytes;int sockfd, client_fd;char buf[BUFFER_SIZE];/*建立socket连接*/if ((sockfd = socket(AF_INET,SOCK_STREAM,0))== -1){perror("socket");exit(1);}printf("Socket id = %dn",sockfd);/*设置sockaddr_in 结构体中相关参数*/server_sockaddr.sin_family = AF_INET;server_sockaddr.sin_port = htons(PORT);server_sockaddr.sin_addr.s_addr = INADDR_ANY;bzero(&(server_sockaddr.sin_zero), 8);int i = 1;/* 使得重复使用本地地址与套接字进行绑定 */setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));/*绑定函数bind*/if (bind(sockfd, (struct sockaddr *)&server_sockaddr, sizeof(struct sockaddr))== -1){perror("bind");exit(1);}printf("Bind success!n");/*调用listen函数*/if (listen(sockfd, MAX_QUE_CONN_NM) == -1){perror("listen");exit(1);}printf("Listening....n");/*调用accept函数,等待客户端的连接*/if ((client_fd = accept(sockfd, (struct sockaddr *)&client_sockaddr, &sin_size)) == -1){perror("accept");exit(1);}/*调用recv函数接收客户端的请求*/memset(buf , 0, sizeof(buf));if ((recvbytes = recv(client_fd, buf, BUFFER_SIZE, 0)) == -1){perror("recv");exit(1);}printf("Received a message: %sn", buf);if ((sendbytes = send(sockfd, buf, strlen(buf), 0)) == -1){perror("send");exit(1);}close(sockfd);exit(0);}客户端:/*client.c*/#include #include #include #include #include #include #include #include #include #define PORT4321#define BUFFER_SIZE 1024int main(int argc, char *argv[]){int sockfd, sendbytes;char buf[BUFFER_SIZE];struct hostent *host;struct sockaddr_in serv_addr;if(argc < 3){fprintf(stderr,"USAGE: ./client Hostname(or ip address) Textn");exit(1);}/*地址解析函数*/if ((host = gethostbyname(argv[1])) == NULL){perror("gethostbyname");exit(1);}memset(buf, 0, sizeof(buf));sprintf(buf, "%s", argv[2]);/*创建socket*/if ((sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1){perror("socket");exit(1);}/*设置sockaddr_in 结构体中相关参数*/serv_addr.sin_family = AF_INET;serv_addr.sin_port = htons(PORT);serv_addr.sin_addr = *((struct in_addr *)host->h_addr);bzero(&(serv_addr.sin_zero), 8);/*调用connect函数主动发起对服务器端的连接*/if(connect(sockfd,(struct sockaddr *)&serv_addr, sizeof(struct sockaddr))== -1){perror("connect");exit(1);}/*发送消息给服务器端*/if ((sendbytes = send(sockfd, buf, strlen(buf), 0)) == -1){perror("send");exit(1);}if ((recvbytes = recv(sockfd, buf, BUFFER_SIZE, 0)) == -1){perror("recv");exit(1);}close(sockfd);exit(0); }

求TCP/IP client server socket的JAVA代码
我这刚好有一个,给你参考一下:(分客户端和服务器两个小程序) //客户端程序及聊天室的图形用户界面import java.awt.event.*;import javax.swing.*;import java.io.*;import java.net.InetAddress;import java.net.Socket;public class ChatTCPSocketJFrame extends JFrame implements ActionListener{private String name; //网名private Socket socket; //TCP Socket对象private JTextArea text_receiver; //显示对话内容的文本区private JTextField text_sender;//输入发送内容的文本行private JButton button_send,button_leave;//发送和离线按钮private PrintWriter cout;//字符输出流对象public ChatTCPSocketJFrame(String name, Socket socket) throws IOException//提供图形用户界面{super("聊天室"+name+""+InetAddress.getLocalHost()+" : "+socket.getLocalPort());this.setBounds(320,240,400,240);this.setDefaultCloseOperation(EXIT_ON_CLOSE);this.text_receiver = new JTextArea();this.text_receiver.setEditable(false); //文本区不可编辑this.getContentPane().add(new JScrollPane(this.text_receiver));JPanel panel = new JPanel();this.getContentPane().add(panel,"South");this.text_sender = new JTextField(16);panel.add(this.text_sender);button_send = new JButton("发送");panel.add(button_send);button_send.addActionListener(this);button_leave = new JButton("离线");panel.add(button_leave);button_leave.addActionListener(this);this.setVisible(true);this.name = name;this.socket = socket;this.cout = new PrintWriter(socket.getOutputStream(),true);//获得Socket对象的输出流,立即flushthis.cout.println(name); //发送自己网名给对方BufferedReader cin=new BufferedReader(new InputStreamReader(socket.getInputStream()));//获得Socket对象的输入流,创建字符输入流String aline=cin.readLine(); //接收到对方网名text_receiver.append("连接"+aline+"成功"+"rn"); //显示对方发来的内容aline= cin.readLine();while (aline!=null && !aline.equals("bye"))//从输入流接收对方发来的字符串{//"bye"是约定的离线信息text_receiver.append(aline+"rn");//显示对方发来的内容aline= cin.readLine();}cin.close();cout.close();socket.close();//关闭Socket连接button_send.setEnabled(false);button_leave.setEnabled(false);}public ChatTCPSocketJFrame(String name, String host, int port) throws IOException //客户端{this(name, new Socket(host, port));//客户端向指定主机的端口发出TCP连接请求}public void actionPerformed(ActionEvent e){if (e.getSource()==button_send)//发送按钮{this.cout.println(name+" 说:"+text_sender.getText()); //通过流发送给对方text_receiver.append("我说:"+text_sender.getText()+"n");text_sender.setText("");}if (e.getSource()==button_leave) //离线{text_receiver.append("我离线n");this.cout.println(name+"离线n"+"bye");//发送给对方离线约定button_send.setEnabled(false);button_leave.setEnabled(false);}}public static void main(String args[]) throws IOException{new ChatTCPSocketJFrame("小蜜蜂", "127.0.0.1", 2001);}}//服务端程序import java.net.*;import java.io.*;public class ChatTCPServer{public ChatTCPServer(int port, String name) throws IOException //约定端口、网名{//本机IP地址和指定端口构成服务端的SocketServerSocket server = new ServerSocket(port);//ServerSocket提供TCP连接服务Socket client = server.accept(); //等待接收客户端的连接申请new ChatTCPSocketJFrame(name,client);//服务端的聊天室,图形用户界面同客户端server.close();}public static void main(String args[]) throws IOException{new ChatTCPServer(2001, "花仙子");//启动服务端,约定端口,指定网名} }
到底要表达什么意思嘛
生活(

socket 客户端可以向服务器端接收和发送文件,代码怎么写
之前写过这样的一个小程序,我发布在自己的博客上:http://www.zhouhaibing.com/blog/archive/8Server.c#include #include #include #include // for file read#include #include int main() { /* load the initializer library */ WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); /* list the each fields of wsaData */ // printf("wVersion: %dn", wsaData.wVersion); // 514 // printf("wHighVersion: %dn", wsaData.wHighVersion); // 514 // printf("iMaxSockets: %dn", wsaData.iMaxSockets); // 0 // printf("iMaxUdpDg: %dn", wsaData.iMaxUdpDg); // 0 /* you may not print the lpVendorInfo */ // printf("szDescription: %sn", wsaData.szDescription); // WinSock 2.0 // printf("szSystemStatus: %sn", wsaData.szSystemStatus); // Running /* create socket(address family, type, protocol) */ int socket_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); /* initialize the addrinfo hints */ struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; hints.ai_flags = AI_PASSIVE; struct addrinfo *result = nullptr; /* by hints, and then get the result(a linked list, see fields below) */ getaddrinfo(NULL, "8080", &hints, &result); /* the member fiekds of result */ // printf("ai_family: %dn", result->ai_family); // 2 // printf("ai_socktype: %dn", result->ai_socktype); // 1 // printf("ai_protocol: %dn", result->ai_protocol); // 6 // printf("ai_flags: %dn", result->ai_flags); // 0 // printf("ai_canonname: %sn", result->ai_canonname); // (null) // printf("ai_a ddrlen: %dn", result->ai_addrlen); // 16 // printf("ai_addr->sa_family: %dn", result->ai_addr->sa_family); // 2 // printf("ai_addr->sa_data: %sn", result->ai_addr->sa_data); // // printf("ai_next: %xn", result->ai_next); // 0 /* bind the socket to a address */ /* bind(socket, sockaddr name, name len) */ bind(socket_fd, result->ai_addr, result->ai_addrlen); freeaddrinfo(result); /* listen the socket */ /* listen(socket, backlog) */ listen(socket_fd, SOMAXCONN); /* 0x7fffffff */ while(true) { /* accept a connection */ /* accept(socket, addr, addrlen) */ int client_fd = accept(socket_fd, nullptr, 0); printf("New Connection Eastablished...n"); /* Now we send the source code of this file to client */ std::ifstream fin("c:\source.cpp"); /* store it into a buffer. */ while (fin.good()) { // I rememeber there is a method called getline std::string s; getline(fin, s); // we need a new line s = s + 'n'; send(client_fd, s.c_str(), s.size(), 0); } fin.close(); /* close client socket */ closesocket(client_fd); } /* may be never invoked */ closesocket(socket_fd); WSACleanup(); return 0;}Client.c#include #include #include #include int main() { /* load the initializer library */ WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); /* create socket */ int socket_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); /* connect */ sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr("127.0.0.1"); addr.sin_port = htons(8080); /* connect(socket, sockaddr, namelen) */ connect(socket_fd, (sockaddr*)&addr, sizeof(addr)); /* buffer memory */ char buf[1024]; /* open a file for write */ std::ofstream fout("source.cpp", std::ios_base::trunc); while (true) {int read = recv(socket_fd, buf, 1024, 0); if (read == 0) { fout.close(); printf("Connection Closed...n"); break; } if (read > 1024) { printf("Buffer Overflow...n"); } else { buf[read - 1] = 0; /* now we can print the bytes from server */ fout << buf << std::endl; } } /* close socket */ closesocket(socket_fd); WSACleanup(); return 0;}

用c语言写个 socket tcp 的
#include
#include #include #pragma comment(lib,"ws2_32.lib")typedef struct{SOCKET accpt;int lock;}Arg;void *transfer(void *arg){Arg * info = (Arg *)arg;SOCKET clientSock;char recvbuf[102];char sendBuf[] = "10";int ret;memcpy(&clientSock,(void*)&info->accpt,sizeof(clientSock));info->lock =1;while (TRUE){ret = send(clientSock,sendBuf,2,0);if (ret == -1){break;}ret = recv(clientSock,recvbuf,102,0);printf("%sn",recvbuf);}return (void *)0;}void* timer(void *arg){time_t last = time(NULL);time_t now;int i = 20;while(i--){now= time(NULL);if(now - last == 1){printf("1s past!n");last = now;}Sleep(500);}printf("timer exit.n");return (void *)0;}int main(void) {WSADATA wsaData;SOCKET ListenSocket;SOCKADDR_IN service,client;int len = sizeof(client);Arg argument;pthread_t tid;char sendBuf[] = "ID=2;WHAT=host";int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);if (iResult != NO_ERROR) {printf("Error at WSAStartup()n");return 1;}ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);if (ListenSocket == INVALID_SOCKET) {printf("Error at socket(): %ldn", WSAGetLastError());WSACleanup();return 1;}service.sin_family = AF_INET;service.sin_addr.s_addr = inet_addr("127.0.0.1");service.sin_port = htons(27115);if (bind( ListenSocket,(SOCKADDR*) &service,sizeof(service)) == SOCKET_ERROR) {printf("bind() failed.n");closesocket(ListenSocket);WSACleanup();return 1;}if (listen( ListenSocket, 1 ) == SOCKET_ERROR) {printf("Error listening on socket.n");closesocket(ListenSocket);WSACleanup();return 1;}argument.lock = 1;printf("Waiting for client to connect...n");pthread_create(&tid,NULL,timer,NULL);while(TRUE){argument.accpt = accept( ListenSocket, (SOCKADDR*)&client, &len );if (argument.accpt == INVALID_SOCKET) {printf("accept failed: %dn", WSAGetLastError());closesocket(ListenSocket);WSACleanup();return 1;} else {printf("accept%s:%dn",inet_ntoa(client.sin_addr),client.sin_port);while (!argument.lock);argument.lock = 0;//sendto(argument.accpt,sendBuf,sizeof(sendBuf),0,(SOCKADDR*)&client,len);pthread_create(&tid,NULL,transfer,&argument);//send(AcceptSocket,sendBuf,sizeof(sendBuf),0);}}// No longer need server socketclosesocket(ListenSocket);WSACleanup();return 0;}发送数据格式按需求。可以发送字符串,也可以发送结构体。如果发送结构体的话,要注意序列化和反序列化。程序例子是服务器对每个客户端的connect动作起一个线程去交互。还有一个线程是定时器。

本文由 在线网速测试 整理编辑,转载请注明出处。