`
memorymyann
  • 浏览: 271967 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

java 和 linux c udp通信的样例

阅读更多

一个简单的例子

 

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);
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics