Java和C都是常見的編程語言,它們都支持socket通信,通過socket通信可以實現進程間的通信和數據傳輸。下面我們來介紹Java和C語言如何使用socket通信。
首先,我們來看看C語言如何使用socket通信。C語言中的socket通信需要使用socket()、bind()、listen()、accept()、send()和recv()等函數。下面是一個簡單的C語言socket通信代碼:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#define PORT 8888
int main(void) {
int server_fd, new_socket;
struct sockaddr_in server_addr, client_addr;
char buffer[1024] = {0};
int opt = 1;
int addr_len = sizeof(server_addr);
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket failed");
exit(EXIT_FAILURE);
}
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons( PORT );
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0) {
perror("listen");
exit(EXIT_FAILURE);
}
if ((new_socket = accept(server_fd, (struct sockaddr *)&client_addr, (socklen_t*)&addr_len)) < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
int valread = read( new_socket , buffer, 1024);
printf("%s\n",buffer );
send(new_socket , "Hello from server" , strlen("Hello from server") , 0 );
printf("Hello message sent\n");
return 0;
}
接著,我們來看看Java語言如何使用socket通信。Java語言中的socket通信主要使用java.net包下的Socket和ServerSocket類。下面是一個簡單的Java語言socket通信代碼:
import java.io.*;
import java.net.*;
public class SocketServer {
public static void main(String[] args) throws IOException {
int portNumber = 8888;
try (
ServerSocket serverSocket =
new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println("Received: " + inputLine);
out.println("Hello from server");
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
總的來說,無論是C語言還是Java語言,都可以通過socket通信,實現進程間通信和數據傳輸。以上是關于Java和C語言socket通信的簡單介紹和示例代碼,希望對大家有所幫助。