手写UDP客户端和服务端

JAVA ZMAS 86℃ 0评论

//客户端
package recive;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Scanner;

import javax.swing.SortingFocusTraversalPolicy;

public class Send {

public static void main(String[] args) {

DatagramSocket socket=null;
Scanner scanner=new Scanner(System.in);
try {
//发数据
String string=null;
DatagramPacket datagramPacket=null;
while(true){
string=scanner.next();
if(string.equals(1)){
break;
}
datagramPacket=new DatagramPacket(string.getBytes(), string.getBytes().length,InetAddress.getByName(“127.0.0.1”),2019);
socket=new DatagramSocket();
socket.send(datagramPacket);
//接数据
//socket=new DatagramSocket(datagramPacket.getPort());
byte[]bs=new byte[1024];
DatagramPacket datagramPacket2=new DatagramPacket(bs, bs.length);
socket.receive(datagramPacket);
//打印输出
String srString=new String(datagramPacket.getData(),0,datagramPacket.getLength());
System.out.println(srString);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(socket!=null){
socket.close();
}
}

}
}
//服务端
package recive;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Scanner;

/*
* 1 快递点 (接收方的快递点 需要设定端口号, 以便于接收的时候知道是否由该socket 接收)
* 2. 接收发送过来的数据
* 3. 将数据获取出来
*
* 4. 关socket
*/
public class Recive {

public static void main(String[] args) {
// 1 快递点
DatagramSocket socket =null;
Scanner scanner=new Scanner(System.in);
// socket = new DatagramSocket(2019);
try {
socket = new DatagramSocket(2019);
while(true){
//socket = new DatagramSocket(2019);
// socket = new DatagramSocket(2019);
// 2. 接收发送过来的数据
// 单独准备一个空箱子 接收 发送方发送过来的额数据
byte[] buf = new byte[1024];
DatagramPacket p = new DatagramPacket(buf, buf.length);
socket.receive(p);// receive 是将接收到的数据 放到 接收方自己准备的空箱子中
// receive 如果等不到 发送方发送数据, 则会阻塞程序向下执行, 知道接收到发送方发送过来的数据

String string = new String(p.getData(),0,p.getLength());
System.out.println(string);
String string2 =null;

string2 =scanner.next();
if(string.equals(1)){
break;
}
DatagramPacket packet = new DatagramPacket(string2.getBytes(), string2.getBytes().length, p.getAddress(), p.getPort());
socket.send(packet);
}

} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(socket!=null){
socket.close();
}
}

}
}

转载请注明:ZMAS‘S blog » 手写UDP客户端和服务端

喜欢 (4)
发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址