java怎么操作无线网卡_java成神之——网络编程基本操作

网络编程

获取ip

InetAddress id = InetAddress.getLocalHost(); // InetAddress id = InetAddress.getByName("www.baidu.com");

System.out.println(id); // DESKTOP-S2V8PJF/192.168.0.35

System.out.println(id.getHostName()); // DESKTOP-S2V8PJF

System.out.println(id.getHostAddress()); // 192.168.0.35

UDP程序示例

发送端

public class Send {

public static void main(String[] args) {

try {

byte[] sendData = "发送的数据".getBytes();

InetAddress id = InetAddress.getByName("127.0.0.1");

DatagramPacket dp = new DatagramPacket(sendData, sendData.length, id, 9000);

DatagramSocket ds = null;

try {

ds = new DatagramSocket();

try {

ds.send(dp);

} catch (IOException e) {

e.printStackTrace();

}

} catch (SocketException e) {

e.printStackTrace();

} finally {

ds.close();

}

} catch (UnknownHostException e) {

e.printStackTrace();

}

}

}

接收端

public class Receive {

public static void main(String[] args) {

DatagramSocket ds = null;

DatagramPacket dp = null;

byte[] receiveData = new byte[1024];

try {

ds = new DatagramSocket(9000);

dp = new DatagramPacket(receiveData, receiveData.length);

try {

ds.receive(dp);

System.out.println("由" + dp.getAddress().getHostAddress()+ ":" + dp.getPort() + "发送的数据->" + new String(receiveData, 0, dp.getLength()));

} catch (IOException e) {

e.printStackTrace();

}

} catch (SocketException e) {

e.printStackTrace();

}finally {

ds.close();

}

}

}

TCP程序

客户端

public class ClientSide {

public static void main(String[] args) {

Socket so;

OutputStream os;

try {

so = new Socket("127.0.0.1", 9000);

os = so.getOutputStream();

os.write("我是 客户端".getBytes()); // 给服务器发送数据

InputStream in = so.getInputStream();

byte[] data = new byte[1024];

int len = in.read(data);

System.out.println(new String(data, 0, len)); // 接受服务器数据

so.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

服务端

public class ServerSide {

public static void main(String[] args) {

ServerSocket ss;

Socket so;

OutputStream os;

try {

ss = new ServerSocket(9000);

so = ss.accept();

InputStream in = so.getInputStream();

byte[] data = new byte[1024];

int len = in.read(data);

System.out.println(new String(data, 0, len)); // 接受客户端数据

os = so.getOutputStream();

os.write("知道了".getBytes()); // 发送数据给客户端

os.close();

so.close();

ss.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

结语

本文章是java成神的系列文章之一

如果你想知道,但是本文没有的,请下方留言

我会第一时间总结出来并发布填充到本文

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值