日期:2014-05-16 浏览次数:20796 次
一个简单的例子
?
java段(客户端)
package udpclient;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Main {
??? /**
??? ?* @param args
??? ?*/
??? public static void main(String[] args) {
??? ??? String sendContent = "hello world";
??? ??? byte[] buffer = sendContent.getBytes();
??? ???
??? ??? DatagramSocket ds = null;
??? ??? DatagramPacket dp = null;
??? ??? try {
??? ??? ??? ds = new DatagramSocket();
??? ??? ??? dp = new DatagramPacket(buffer, buffer.length, InetAddress.getByName("192.168.1.157"), 9548);
??? ??? ??? ds.send(dp);
??? ??? } catch (Exception e) {
??? ??? ??? e.printStackTrace();
??? ??? } finally {
??? ??? ??? if(ds != null)
??? ??? ??? ??? ds.close();
??? ??? }
??? }
}
?
linux端
#include "stdio.h"
#include "stdlib.h"
#include "sys/types.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "arpa/inet.h"
#include "netdb.h"
#include "string.h"
#define PORT 9548
#define MAXSIZE 1024
int main() {
??????? int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
??????? struct sockaddr_in my_socket;
??????? bzero(&my_socket, sizeof(struct sockaddr_in));
??????? my_socket.sin_family = AF_INET;
??????? my_socket.sin_addr.s_addr = htonl(INADDR_ANY);
??????? my_socket.sin_port = htons(PORT);
??????? bind(sockfd, (struct sockaddr *)&my_socket, sizeof(struct sockaddr_in));
??????? char buf[MAXSIZE];
??????? int n = read(sockfd, buf, MAXSIZE);
??????? buf[n] = '\0';
??????? printf("%s\n", buf);
??????? exit(0);
}