——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——-
DatagramSocket socket = new DatagramSocket(6666); //创建socket相当于创建码头
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024); //创建packet相当于创建集装箱
while(true) {
socket.receive(packet); //接收货物
byte[] arr = packet.getData();
int len = packet.getLength();
String ip = packet.getAddress().getHostAddress();
System.out.println(ip + ":" + new String(arr,0,len));
}
发送端Send
DatagramSocket socket = new DatagramSocket(); //创建socket相当于创建码头
Scanner sc = new Scanner(System.in);
while(true) {
String str = sc.nextLine();
if("quit".equals(str))
break;
DatagramPacket packet = //创建packet相当于创建集装箱
new DatagramPacket(str.getBytes(), str.getBytes().length, InetAddress.getByName("127.0.0.1"), 6666);
socket.send(packet); //发货
}
socket.close();
A发送和接收在一个窗口完成
public class Demo3_MoreThread {
/**
* @param args
*/
public static void main(String[] args) {
new Receive().start();
new Send().start();
}
}
class Receive extends Thread {
public void run() {
try {
DatagramSocket socket = new DatagramSocket(6666); //创建socket相当于创建码头
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024); //创建packet相当于创建集装箱
while(true) {
socket.receive(packet); //接收货物
byte[] arr = packet.getData();
int len = packet.getLength();
String ip = packet.getAddress().getHostAddress();
System.out.println(ip + ":" + new String(arr,0,len));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Send extends Thread {
public void run() {
try {
DatagramSocket socket = new DatagramSocket(); //创建socket相当于创建码头
Scanner sc = new Scanner(System.in);
while(true) {
String str = sc.nextLine();
if("quit".equals(str))
break;
DatagramPacket packet = //创建packet相当于创建集装箱
new DatagramPacket(str.getBytes(), str.getBytes().length, InetAddress.getByName("127.0.0.1"), 6666);
socket.send(packet); //发货
}
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package cn.itcast.udp;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Demo4_GuiChat extends Frame {
private TextArea sendText;
private TextArea viewText;
private TextField tf;
private Button send;
private Button clear;
private Button log;
private Button shake;
private DatagramSocket socket;
private BufferedWriter bw;
/**
* @param args
*/
public Demo4_GuiChat() {
init();
southPanel();
centerPanel();
event();
}
private void event() {
this.addWindowListener(new WindowAdapter() { //添加窗体监听
@Override
public void windowClosing(WindowEvent e) { //关闭窗口
try {
socket.close();
bw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.exit(0);
}
});
send.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
send();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
clear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
viewText.setText("");
}
});
log.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
logFile();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
shake.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
send(new byte[]{-1},tf.getText());
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
sendText.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
try {
send();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
}
/*
* 震动
*/
private void shake() throws InterruptedException {
int x = this.getLocation().x; //获取x坐标
int y = this.getLocation().y; //获取y坐标
for(int i = 0; i < 20; i++) {
this.setLocation(x + 20, y + 20);
Thread.sleep(20);
this.setLocation(x - 20, y + 20);
Thread.sleep(20);
this.setLocation(x + 20, y - 20);
Thread.sleep(20);
this.setLocation(x - 20, y - 20);
Thread.sleep(20);
this.setLocation(x, y);
}
}
/*
* 获取聊天记录
*/
private void logFile() throws IOException {
bw.flush();
FileInputStream fis = new FileInputStream("config.txt");
ByteArrayOutputStream baos = new ByteArrayOutputStream(); //把内存当作缓冲区
int b;
while((b = fis.read()) != -1) {
baos.write(b);
}
fis.close();
String str = baos.toString(); //将字节数组中数据转换成字符串
//byte[] arr = baos.toByteArray(); //获取字节数据
//String str = new String(arr); //转换成字符串
viewText.setText(str);
}
private void send(byte[] arr, String ip) throws IOException {
DatagramPacket packet =
new DatagramPacket(arr, arr.length, InetAddress.getByName(ip), 6666);
socket.send(packet);
}
/*
* 发送文本信息,将发送区域的内容,发送到指定ip地址去,并显示到显示区域
*/
private void send() throws IOException {
String message = sendText.getText(); //获取发送区域的文本信息
String ip = tf.getText(); //获取ip地址
ip = ip.trim().length() == 0 ? "255.255.255.255" : ip; //如果什么也没写默认是对所有人说
//DatagramSocket socket = new DatagramSocket(); //创建socket,相当于创建的是码头
/*DatagramPacket packet =
new DatagramPacket(message.getBytes(), message.getBytes().length, InetAddress.getByName(ip), 6666);
socket.send(packet); */ //发送数据
send(message.getBytes(),ip);
String time = getCurrentTime();
String str = time + "我对:" + (ip.equals("255.255.255.255")? "所有人" : ip) + "说:\r\n" + message + "\r\n\r\n";
viewText.append(str); //将数据添加到显示区域
bw.write(str); //将数据写到文本上
sendText.setText(""); //将发送区域设置为空
//socket.close(); //关闭scoket,开一次,在这里关闭
}
/*
* 获取当前时间
*/
private String getCurrentTime() {
Date d = new Date(); //创建当前的时间对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");//创建格式化对象
return sdf.format(d); //格式化日期对象
}
private void centerPanel() {
Panel center = new Panel(); //创建中间的Panel
sendText = new TextArea(5,1);
viewText = new TextArea();
viewText.setEditable(false); //设置为不可编辑
viewText.setBackground(Color.WHITE); //设置背景颜色为白色
sendText.setFont(new Font("yyy", Font.PLAIN, 15)); //设置字体
viewText.setFont(new Font("yyy", Font.PLAIN, 15));
center.setLayout(new BorderLayout()); //将布局管理器设置为边界布局管理器
center.add(sendText,BorderLayout.SOUTH); //将发送的文本区域放在Panel的南边
center.add(viewText,BorderLayout.CENTER); //将显示的文本区域放在Panel的中间
this.add(center,BorderLayout.CENTER);
}
private void southPanel() {
Panel south = new Panel(); //创建南边的Panel
tf = new TextField(15);
tf.setText("127.0.0.1"); //设置初始ip
send = new Button("发 送");
clear = new Button("清 屏");
log = new Button("记 录");
shake = new Button("震 动");
south.add(tf);
south.add(send);
south.add(clear);
south.add(log);
south.add(shake);
this.add(south,BorderLayout.SOUTH); //把Panel放在Frame的南边
}
private void init() {
this.setSize(400, 600);
this.setLocation(500, 50);
this.setTitle("GUI聊天室");
new Receive().start();
try {
socket = new DatagramSocket();
bw = new BufferedWriter(new FileWriter("config.txt",true));
} catch (IOException e) {
e.printStackTrace();
}
this.setVisible(true);
}
/*
* 定义接收方
*/
private class Receive extends Thread {
public void run() {
try {
DatagramSocket socket = new DatagramSocket(6666);
DatagramPacket packet = new DatagramPacket(new byte[8192], 8192);
while(true) {
socket.receive(packet);
byte[] arr = packet.getData(); //获取数据
int len = packet.getLength(); //获取有效的字节
if(arr[0] == -1 && len == 1) {
shake(); //调用震动方法
continue; //终止本次循环,继续下次循环
}
String ip = packet.getAddress().getHostAddress(); //获取ip地址
String message = new String(arr,0,len); //将数据转换成字符串
String time = getCurrentTime(); //获取当前时间
String str = time + " " + ip + "对我说:\r\n" + message + "\r\n\r\n"; //抽取局部变量 alt + shift + l
viewText.append(str);
bw.write(str);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Demo4_GuiChat();
}
}
package cn.itcast.udp;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;
public class Demo2_Send {
/**
* 发送Send
* 创建DatagramSocket, 随机端口号
* 创建DatagramPacket, 指定数据, 长度, 地址, 端口
* 使用DatagramSocket发送DatagramPacket
* 关闭DatagramSocket
* @throws IOException
*/
public static void main(String[] args) throws IOException {
DatagramSocket socket = new DatagramSocket(); //创建socket相当于创建码头
Scanner sc = new Scanner(System.in);
while(true) {
String line = sc.nextLine(); //将键盘录入的字符串存储在line中
if(line.equals("quit")) {
break;
}
DatagramPacket packet = //创建packet相当于创建集装箱
new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("127.0.0.1"), 8888);
socket.send(packet); //发送数据
}
socket.close(); //关闭socket
}
}
见上
见上
private void shake() throws InterruptedException {
int x = this.getLocation().x; //获取x坐标
int y = this.getLocation().y; //获取y坐标
for(int i = 0; i < 20; i++) {
this.setLocation(x + 20, y + 20);
Thread.sleep(20);
this.setLocation(x - 20, y + 20);
Thread.sleep(20);
this.setLocation(x + 20, y - 20);
Thread.sleep(20);
this.setLocation(x - 20, y - 20);
Thread.sleep(20);
this.setLocation(x, y);
}
}
//见上
客户端
Socket socket = new Socket("127.0.0.1", 9999); //创建Socket指定ip地址和端口号
InputStream is = socket.getInputStream(); //获取输入流
OutputStream os = socket.getOutputStream(); //获取输出流
BufferedReader br = new BufferedReader(new InputStreamReader(is));
PrintStream ps = new PrintStream(os);
System.out.println(br.readLine());
ps.println("我想报名就业班");
System.out.println(br.readLine());
ps.println("下期");
socket.close();
服务端
ServerSocket server = new ServerSocket(9999); //创建服务器
Socket socket = server.accept(); //接受客户端的请求
InputStream is = socket.getInputStream(); //获取输入流
OutputStream os = socket.getOutputStream(); //获取输出流
BufferedReader br = new BufferedReader(new InputStreamReader(is));
PrintStream ps = new PrintStream(os);
ps.println("欢迎咨询传智播客");
System.out.println(br.readLine());
ps.println("报满了,请报下一期吧");
System.out.println(br.readLine());
server.close();
socket.close();
ServerSocket server = new ServerSocket(9999); //创建服务器
while(true) {
final Socket socket = server.accept(); //接受客户端的请求
new Thread() {
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("欢迎");
System.out.println(br.readLine());
ps.println("好的");
System.out.println(br.readLine());
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
package cn.itcast.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Test1_Client {
/**
* 客户端向服务器写字符串(键盘录入),服务器(多线程)将字符串反转后写回,客户端再次读取到是反转后的字符串
* @throws Exception
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, Exception {
Socket socket = new Socket("127.0.0.1", 5432); //创建客户端的Socket
Scanner sc = new Scanner(System.in);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println(sc.nextLine()); //把键盘录入的字符串写到服务器去
System.out.println(br.readLine()); //将服务器反转后的结果读取
socket.close();
}
}
package cn.itcast.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Test1_Server {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(5432);
System.out.println("服务器启动,绑定54321端口");
while(true) {
final Socket socket = server.accept();
new Thread() {
public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
String line = br.readLine();
line = new StringBuilder(line).reverse().toString(); //将客户端写过来的字符串反转
ps.println(line);
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
}
package cn.itcast.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Test1_UploadClient {
/**
* @param args
* @throws Exception
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, Exception {
//1,获取要上传的文件
File file = getFile();
//2,将文件名上传给服务器
Socket socket = new Socket("127.0.0.1", 12345); //创建客户端的Socket,访问12345端口
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));//将输入字节流包装成字符流
PrintStream ps = new PrintStream(socket.getOutputStream());//将字节输出流包装成打印流
ps.println(file.getName()); //将文件名写到服务器
//6,接收结果,对结果进行判断如果存在,就不上传,将方法返回socket结束
String result = br.readLine(); //将服务器的结果读取出来
if("存在".equals(result)) {
System.out.println("文件已经存在,请不要重复上传");
socket.close();
return;
}
//7,不存在,就读取这个文件,并把文件上传服务器
FileInputStream fis = new FileInputStream(file);
byte[] arr = new byte[8192];
int len;
while((len = fis.read(arr)) != -1) {
ps.write(arr, 0, len);
}
fis.close();
socket.close();
}
/*
* 获取文件
*/
public static File getFile() {
Scanner sc = new Scanner(System.in); //创建键盘录入对象
System.out.println("请输入一个文件路径:");
while(true) {
String line = sc.nextLine(); //将文件路径存储在line中
File file = new File(line); //将文件路径封装成File对象
if(!file.exists()) {
System.out.println("重输:");
}else if(file.isDirectory()) {
System.out.println("重输:");
}else {
return file; //返回文件
}
}
}
}
package cn.itcast.test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Test1_UploadServer {
/**
* @param args
* 客户端向服务器上传文件
* @throws IOException
*/
public static void main(String[] args) throws IOException {
//3,创建多线程的服务器
ServerSocket server = new ServerSocket(12345); //创建服务器,绑定12345端口
System.out.println("服务器启动,绑定12345端口");
while(true) {
final Socket socket = server.accept(); //接受客户端的请求,返回一个Socket
new Thread() { //每接受一个请求,就创建一个线程
public void run() {
try {
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));//将输入字节流包装成字符流
PrintStream ps = new PrintStream(socket.getOutputStream());//将字节输出流包装成打印流
//4,将文件名读取出来
String fileName = br.readLine();
File dir = new File("Upload"); //将文件夹路径封装到File对象
dir.mkdir(); //创建文件夹
File file = new File(dir,fileName); //将客户端上传的文件放在Upload下
//5,对文件名进行判断,将结果写回给客户端,要么存在,要么不存在
if(file.exists()) {
ps.println("存在");
socket.close();
return;
}else {
ps.println("不存在");
}
//8,将客户端上传的文件读取出来,写到本地
FileOutputStream fos = new FileOutputStream(file);
byte[] arr = new byte[8192];
int len;
while((len = is.read(arr)) != -1) {
fos.write(arr, 0, len);
}
fos.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
}