服务器端代码 MyServer.java
import java.io.*;
import java.net.*;
import java.util.*;
public class MyServer {
public static void main(String[] args) throws IOException{
ServerSocket server=new ServerSocket(5678);
while(true){
Socket client=server.accept();
BufferedReader in=new BufferedReader(new InputStreamReader(client.getInputStream()));
String str=in.readLine();
System.out.println(str);
client.close();
}
}
}
客户端client.c代码:
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main() {
int sockfd;
int len;
struct sockaddr_in address;
int result;
char ch[100];
while(1){
sockfd = socket(AF_INET,SOCK_STREAM,0);
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("192.168.11.169");
address.sin_port = htons(5678);
len = sizeof(address);
result = connect(sockfd,(struct sockaddr *)&address,len);
if(result == -1) {
perror("oops:client\n");
exit(1);
}
printf("请输入你要传输的数据\n");
gets(ch);
len = strlen(ch);
printf("vcluster %d, %s\n", len, ch);
ch[len] = '\0';
printf("%d, %s\n", len, ch);
write(sockfd,ch,len+1);
close(sockfd);
}
exit(0);
return 0;
}
参考博客: