Java udp socket编程
本文仅实现了客户端发送字符串到服务端,服务端将其转换为大写,再发送给服务端
Java 比c++简单明了得多,直接看代码就可以弄懂了。
服务端
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Arrays;
public class Main {
//服务器
public static void main(String[] args) {
// write your code here
try {
//众所周知,UDP面向数据报
DatagramSocket socket = new DatagramSocket(9527);
byte[] message=new byte[1024];
while (true){
DatagramPacket packet = new DatagramPacket(message,1024);
socket.receive(packet);
InetAddress address = packet.getAddress();
int port = packet.getPort();
byte[] received = packet.getData();
int len = packet.getLength();
for(int i=0;i<len;i++){
if(received[i]>='a'&&received[i]<='z'){
received[i]= (byte) (received[i]-'a'+'A');
}
}
for(int i=0;i<len;i++){
System.out.printf("%c",packet.getData()[i]);
}
System.out.println();
packet.setAddress(address);
packet.setPort(port);
socket.send(packet);
}
} catch (IOException e) {
System.out.println("socket有问题");
}
}
}
客户端
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
Scanner input = new Scanner(System.in);
try {
String words;
while (true) {
words=input.next();
DatagramSocket socket = new DatagramSocket();
byte[] message = words.getBytes();
//InetAddress类用来描述一个IP地址
InetAddress address = InetAddress.getByName("127.0.0.1");
//DatagramPacket是一个数据报包
//port用于表述服务器应用进程的端口号
DatagramPacket packet = new DatagramPacket(message, message.length, address, 9527);
socket.send(packet);
System.out.println("发送成功!");
socket.receive(packet);
int len = packet.getLength();
for(int i=0;i<len;i++){
System.out.printf("%c",packet.getData()[i]);
}
System.out.println();
}
} catch (SocketException e) {
System.out.println("socket有问题");
} catch (UnknownHostException e) {
System.out.println("地址有问题");
}catch (IOException e) {
System.out.println("发送失败了");
}
}
}
如需转载,请注明出处
如有侵权,联系删除
2290713181@qq.com
如有侵权,联系删除
2290713181@qq.com