网络编程:
网络编程其实就是Socket编程,用于网络间通信。具体我们看看怎么使用它吧
我们先来看看怎么利用UDP进行网络之间的通信
实现语言JAVA
发送端:
import java.net.*;
public class Udpsend{
public static void main(String argv[]) throws Exception{
//1.设置udp服务
DatagramSocket ds = new DatagramSocket(8888);
//2.准备数据,并封装在Socketpacket中
byte[] date = "今天学习 Socket!!!!!".getBytes();
DatagramPacket sp = new DatagramPacket(date,date.length,InetAddress.getByName("192.168.0.105"),10000);
//3.通过Socet服务,把已有的数据包发送出去。
ds.send(sp);
//4.关闭资源
ds.close();
}
}
接收端:
import java.net.*;
public class UdpRace {
public static void main() {
//1.建立UDP服务
DatagramSocket ds = new DatagramSocket(10000);
while(true){
//2.建立数据包,用于接收数据
byte[] buff = new byte[1024];
DatagramPacket dp = new DatagramPacket(buff,buff.length);
//3.利用UDP服务revice方法接收数据
ds.revice(dp);
String s = dp.getAddress().getHostAddress();
String d = new String ( dp.getData(),0,dp.getLength()) ;
int p = dp.getPort();
System.out.print(s+d+p);
}
//4.关闭资源
ds.close();
}
}
键盘输入聊天方式:
import java.net.*;
import java.io.*;
class Send implements Runnable{
private DatagramSocket ds;
public Send(DatagramSocket ds) {
this.ds = ds;
}
public void run() {
try{
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(is);
String line = null;
while((line=br.readLine())!=null) {
if("886".equals(line)) {
break;
}
byte[] buf = line.getBytes();
DatagramPacket dp =
new DatagramPacket(buf,buf.length,InetAddress.getByName("192.168.0.105"),10002);
ds.send(dp);
}
}catch(Exception e) {
throw new RuntimeException("发送服务错误");
}
}
}
class Race implements Runnable{
private DatagramSocket ds;
public Race(DatagramSocket ds){
this.ds = ds;
}
public void run(){
try{
while(true){
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf,buf.length);
ds.receive(dp);
String ip = dp.getAddress().getHostAddress();
String data = new String(dp.getData(),0,dp.getLength());
System.out.println(ip+data);
}
}
catch (Exception e){
throw new RuntimeException("接受服务错误");
}
}
}
public class ChatDemo{
public static void main(String[] args) throws Exception{
DatagramSocket sendSocket = new DatagramSocket();
DatagramSocket raceSocket = new DatagramSocket(10002);
new Thread(new Send(sendSocket)).start();
new Thread(new Race(raceSocket)).start();
}
}