UDP 聊天案例
package org.lulu.learn;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Scanner;
/**
* Project: Day16
* Created: Lulu
* Date: 2016/8/17
*/
public class ChatTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("输入对方的IP");
String host = scanner.next();
try {
//获取到目标主机地址
InetAddress target = InetAddress.getByName(host);
//设置程序端口号为 : 10000
DatagramSocket socket = new DatagramSocket(10000);
//接收消息
new Thread(() -> {
byte[] buffer = new byte[1024];
while (true) {
try {
//封装packet数据包, 用于接收
DatagramPacket receiver = new DatagramPacket(buffer, buffer.length);
socket.receive(receiver);//发送数据包
InetAddress address = receiver.getAddress();//得到接收者的IP地址
//如果我发送的目标与当前发送者不同, 自动回复
if(!address.equals(target)) {
receiver.setData("么么哒!".getBytes("UTF-8"));
socket.send(receiver);
}
//打印对方发来的信息
System.out.print(address.getHostAddress() + ": ");
String text = new String(receiver.getData(),receiver.getOffset(), receiver.getLength(), "UTF-8");
System.out.println(text);
//如果对方发来"呵呵"就会停止接收
if (text.equals("呵呵")) {
System.out.println("傻逼退出");
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
//发送信息
//创建发送的数据包
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
//设置发送的目标主机
packet.setAddress(target);
//设置对方程序的端口号
packet.setPort(10000);
//循环发送
while (true) {
String text = scanner.next();
packet.setData(text.getBytes("UTF-8"));
socket.send(packet);
if (text.equals("bye")) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
TCP 聊天案例
ChatRunnable.java
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
/**
* Project: SocketDemo
* Created: Lulu
* Date: 2016/8/17
*/
public class ChatRunable implements Runnable {
private Socket socket;
public ChatRunable(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
InputStream is = socket.getInputStream();
String host = socket.getInetAddress().getHostAddress();
System.out.println(host + "上线了");
InputStreamReader isr = new InputStreamReader(is, "utf-8");
char[] ch = new char[20];
int len;
System.out.print(host + ":");
while ((len = isr.read(ch)) != -1) {
System.out.println(new String(ch, 0, len));
}
// byte[] bytes = new byte[10];
// int length;
// while (((length = is.read(bytes)) != -1)) {
// System.out.println(host + ":" + new String(bytes, 0, length));
// }
System.out.println(host + "下线了");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Server.java
/**
* Project: SocketDemo
* Created: Lulu
* Date: 2016/8/17
*/
public class Server {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(10000);
Socket socket;
System.out.println("=====等待链接=====");
while ((socket = server.accept()) != null) {
// InputStream is = socket.getInputStream();
// byte[] buffer = new byte[1024];
// int length;
// OutputStream os = socket.getOutputStream();
// while ((length = is.read(buffer)) != -1) {
// System.out.println(new String(buffer, 0, length, "utf-8"));
// os.write("服务器收到".getBytes("utf-8"));
// }
//
// //一个链接中断之后才能接收下一个链接
// System.out.println("链接中断");
new Thread(new ChatRunable(socket)).start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Client.java
package org.lulu.learn;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;
/**
* Project: SocketDemo
* Created: Lulu
* Date: 2016/8/17
*/
//客户端的端口是随机分配的
public class Client {
public static void main(String[] args) {
try {
// Socket socket = new Socket("10.0.179.7", 10000);
// Socket socket = new Socket("127.0.0.1", 10000);
// Socket socket = new Socket("10.0.179.178", 10000);
Socket socket = new Socket("10.0.179.74", 10000);
Scanner scanner = new Scanner(System.in);
OutputStream os = socket.getOutputStream();
InputStream is = socket.getInputStream();
String text;
while (true) {
text= scanner.next();
os.write(text.getBytes("utf-8"));
if (text.equals("end")) {
break;
}
//读取服务器响应
// byte[] buffer = new byte[102400];
// int length = is.read(buffer);
// System.out.println(new String(buffer, 0, length, "utf-8"));
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
TCP 文件传输
Server.java
package org.lulu.learn.file_test;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Project: SocketDemo
* Created: Lulu
* Date: 2016/8/17
* 用数据流传输
*/
public class Server {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(10000);
Socket socket;
while ((socket = server.accept()) != null) {
DataInputStream dis = new DataInputStream(socket.getInputStream());
String name = dis.readUTF();
long fileLength = dis.readLong();//文件长度
// //如果小数据可以这样写
// byte[] buffer = new byte[(int) fileLength];
// dis.readFully(buffer);//读满写入
//大文件, 随读随写,
FileOutputStream fos = new FileOutputStream(name);
byte[] buffer = new byte[1024*1024];
int length;
while (fileLength > 0) {
length = dis.read(buffer, 0, (int) Math.min(buffer.length, fileLength));
fileLength -= length;
fos.write(buffer, 0, length);
}
socket.close();
System.out.println("上传成功");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Client.java
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
/**
* Project: SocketDemo
* Created: Lulu
* Date: 2016/8/17
*/
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("10.0.179.178", 10000);
File file = new File("F:\\Video\\Movie\\老九门\\EP22.mp4");
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
dos.writeUTF(file.getName());
dos.writeLong(file.length());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[102400];
int length;
while ((length = fis.read(buffer)) != -1) {
dos.write(buffer, 0, length);
}
System.out.println("上传完毕");
} catch (Exception e) {
e.printStackTrace();
}
}
}