网络编程 UDP TCP
2013年10月03日
⁄ 综合
⁄ 共 2404字 ⁄ 字号
小 中 大
-
//UDP协议
-
public class UdpDemo {
-
-
public static void main(String[] args) throws Exception{
-
-
DatagramSocket send=new DatagramSocket();
-
DatagramSocket receive=new DatagramSocket(10002);
-
-
new Thread(new UdpSend(send)).start();
-
new Thread(new UdpReceive(receive)).start();
-
}
-
-
}
-
-
class UdpSend implements Runnable {
-
private DatagramSocket ds;
-
-
// 1.创建udp对象
-
public UdpSend(DatagramSocket ds) {
-
this.ds = ds;
-
}
-
-
public void run() {
-
try {
-
// 2.确定数据,并封装成数据包
-
BufferedReader bufr = new BufferedReader(new InputStreamReader(
-
System.in));
-
String line = null;
-
while ((line = bufr.readLine()) != null) {
-
if ("886".equals(line)) {
-
break;
-
}
-
byte[] buf = line.getBytes();
-
DatagramPacket dp = new DatagramPacket(buf, buf.length,
-
InetAddress.getByName("127.0.0.1"), 10000);
-
-
// 3. 通过socket服务, 将已有的数据包发送出去。
-
ds.send(dp);
-
}
-
} catch (Exception e) {
-
throw new RuntimeException("发送端失败");
-
}
-
-
}
-
}
-
-
class UdpReceive implements Runnable {
-
-
private DatagramSocket ds;
-
-
// 1.创建udp对象
-
public UdpReceive(DatagramSocket ds) {
-
this.ds = ds;
-
}
-
-
public void run() {
-
try {
-
while (true) {
-
// 2.定义数据包,用于存储数据
-
byte[] buf = new byte[1024];
-
DatagramPacket dp = new DatagramPacket(buf, buf.length);
-
-
// 3. 通过服务的receive方法, 将收到的数据存到数据包中
-
ds.receive(dp);// 阻塞方法
-
-
// 4. 通过数据包的方法获取数据
-
String ip = dp.getAddress().getHostAddress();
-
String data = new String(dp.getData(), 0, dp.getLength());
-
int port = dp.getPort();
-
System.out.println(ip + data + port);
-
}
-
} catch (Exception e) {
-
throw new RuntimeException("接受端失败");
-
}
-
// ds.close();
-
}
-
}
-
//TCP协议
-
class TcpClient {
-
public static void main(String[] args) throws Exception {
-
-
Socket s = new Socket("192.168.1.251", 10003);
-
-
// 为了发送数据,应该获取socket流中的输出流
-
OutputStream out = s.getOutputStream();
-
out.write("11".getBytes());
-
-
InputStream in = s.getInputStream();
-
byte[] buf = new byte[1024];
-
int len = in.read(buf);
-
System.out.println(new String(buf, 0, len));
-
-
s.close();
-
}
-
}
-
-
class TcpServer {
-
public static void main(String[] args) throws Exception {
-
// 建立服务端socket服务,并监听一个端口
-
ServerSocket ss = new ServerSocket(10003);
-
-
// 获取客户端对象
-
Socket s = ss.accept();
-
-
String ip = s.getInetAddress().getHostAddress();
-
-
// 获取客户端发送过来的数据,要使用客户端对象的读取流来读取数据
-