JAVA 网络编程
UDP传输
package com.heima.socket;
import sun.security.util.Length;
import java.net.*;
import java.util.Scanner;
/**
* Code by pureqh on 2021-03-22
*/
public class Demo1_Send {
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
DatagramSocket socket = new DatagramSocket(); //创建socket相当于创建码头
//创建Packet相当于集装箱
while (true) {
String line = sc.nextLine(); //获取键盘录入的字符串
if ("quit".equals(line)){
break;
}
DatagramPacket packet = new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("127.0.0.1"), 6666);
socket.send(packet);
}
socket.close();
}
}
import sun.security.util.Length;
import java.net.*;
import java.util.Scanner;
/**
* Code by pureqh on 2021-03-22
*/
public class Demo1_Send {
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
DatagramSocket socket = new DatagramSocket(); //创建socket相当于创建码头
//创建Packet相当于集装箱
while (true) {
String line = sc.nextLine(); //获取键盘录入的字符串
if ("quit".equals(line)){
break;
}
DatagramPacket packet = new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("127.0.0.1"), 6666);
socket.send(packet);
}
socket.close();
}
}
package com.heima.socket;
import javax.sound.midi.Receiver;
import javax.swing.plaf.basic.BasicTextAreaUI;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Scanner;
/**
* Code by pureqh on 2021-03-22
*/
public class Demo1_Receive {
public static void main(String[] args) throws Exception {
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(); //获取IP地址
int port = packet.getPort();
System.out.println(ip + ":" + port + ":" + new String(arr, 0, len));
}
}
}
import javax.sound.midi.Receiver;
import javax.swing.plaf.basic.BasicTextAreaUI;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.Scanner;
/**
* Code by pureqh on 2021-03-22
*/
public class Demo1_Receive {
public static void main(String[] args) throws Exception {
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(); //获取IP地址
int port = packet.getPort();
System.out.println(ip + ":" + port + ":" + new String(arr, 0, len));
}
}
}
UDP传输多线程
package com.heima.socket;
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
/**
* Code by pureqh on 2021-03-22
*/
public class Demo3_MoreThread {
public static void main(String[] args) {
new Receive().start();
new Send().start();
}
}
class Receive extends Thread{
public void run(){
DatagramSocket socket = null;//创建socket相当于创建码头
try {
socket = new DatagramSocket(6666);
} catch (SocketException e) {
e.printStackTrace();
}
DatagramPacket packet = new DatagramPacket(new byte[1024],1024);//创建packet相当于创建集装箱
while (true) {
try {
socket.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
byte[] arr = packet.getData(); //获取数据
int len = packet.getLength();//获取有效的字节个数
String ip = packet.getAddress().getHostAddress(); //获取IP地址
int port = packet.getPort();
System.out.println(ip + ":" + port + ":" + new String(arr, 0, len));
}
}
}
class Send extends Thread{
public void run(){
Scanner sc = new Scanner(System.in);
DatagramSocket socket = null; //创建socket相当于创建码头
try {
socket = new DatagramSocket();
} catch (SocketException e) {
e.printStackTrace();
}
//创建Packet相当于集装箱
while (true) {
String line = sc.nextLine(); //获取键盘录入的字符串
if ("quit".equals(line)){
break;
}
DatagramPacket packet = null;
try {
packet = new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("127.0.0.1"), 6666);
} catch (UnknownHostException e) {
e.printStackTrace();
}
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
import java.io.IOException;
import java.net.*;
import java.util.Scanner;
/**
* Code by pureqh on 2021-03-22
*/
public class Demo3_MoreThread {
public static void main(String[] args) {
new Receive().start();
new Send().start();
}
}
class Receive extends Thread{
public void run(){
DatagramSocket socket = null;//创建socket相当于创建码头
try {
socket = new DatagramSocket(6666);
} catch (SocketException e) {
e.printStackTrace();
}
DatagramPacket packet = new DatagramPacket(new byte[1024],1024);//创建packet相当于创建集装箱
while (true) {
try {
socket.receive(packet);
} catch (IOException e) {
e.printStackTrace();
}
byte[] arr = packet.getData(); //获取数据
int len = packet.getLength();//获取有效的字节个数
String ip = packet.getAddress().getHostAddress(); //获取IP地址
int port = packet.getPort();
System.out.println(ip + ":" + port + ":" + new String(arr, 0, len));
}
}
}
class Send extends Thread{
public void run(){
Scanner sc = new Scanner(System.in);
DatagramSocket socket = null; //创建socket相当于创建码头
try {
socket = new DatagramSocket();
} catch (SocketException e) {
e.printStackTrace();
}
//创建Packet相当于集装箱
while (true) {
String line = sc.nextLine(); //获取键盘录入的字符串
if ("quit".equals(line)){
break;
}
DatagramPacket packet = null;
try {
packet = new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("127.0.0.1"), 6666);
} catch (UnknownHostException e) {
e.printStackTrace();
}
try {
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
}
}
socket.close();
}
}
UDP聊天图形化界面
package com.heima.socket;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* Code by pureqh on 2021-03-22
*/
public class Demo4_GUIChat extends Frame {
public Demo4_GUIChat(){
init();
southPanel();
centerPanel();
event();
}
public void event() {
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void centerPanel() {
Panel center = new Panel();
TextArea viewText = new TextArea(); //显示的文本区域
TextArea sendText = new TextArea(5,1); //发送的文本区域
center.setLayout(new BorderLayout()); //设置为边界布局管理器
center.add(sendText, BorderLayout.SOUTH); //发送的文本区域放在南边
center.add(viewText,BorderLayout.CENTER); //显示区域放在中间
viewText.setEditable(false); //设置不可以编辑
viewText.setBackground(Color.white); //设置背景颜色
sendText.setFont(new Font("xx",Font.PLAIN,20)); //设置发送区域字体大小
viewText.setFont(new Font("xx",Font.PLAIN,20));
this.add(center,BorderLayout.CENTER); //输入框放中间
}
public void southPanel(){
Panel south = new Panel(); //创建南边的Panel
TextField tf = new TextField(15); //创建文本字段存储IP地址
Button send = new Button("发送"); //创建发送按钮
Button log = new Button("记录"); //创建记录按钮
Button clear = new Button("清屏"); //创建清屏按钮
Button shake = new Button("震动"); //创建震动按钮
south.add(tf);
south.add(send);
south.add(log);
south.add(clear);
south.add(shake);
this.add(south,BorderLayout.SOUTH); //将Paneal放在fream的南边
}
public void init() {
this.setLocation(500,50);
this.setSize(400,600);
this.setVisible(true);
}
public static void main(String[] args) {
new Demo4_GUIChat();
}
}
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* Code by pureqh on 2021-03-22
*/
public class Demo4_GUIChat extends Frame {
public Demo4_GUIChat(){
init();
southPanel();
centerPanel();
event();
}
public void event() {
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
public void centerPanel() {
Panel center = new Panel();
TextArea viewText = new TextArea(); //显示的文本区域
TextArea sendText = new TextArea(5,1); //发送的文本区域
center.setLayout(new BorderLayout()); //设置为边界布局管理器
center.add(sendText, BorderLayout.SOUTH); //发送的文本区域放在南边
center.add(viewText,BorderLayout.CENTER); //显示区域放在中间
viewText.setEditable(false); //设置不可以编辑
viewText.setBackground(Color.white); //设置背景颜色
sendText.setFont(new Font("xx",Font.PLAIN,20)); //设置发送区域字体大小
viewText.setFont(new Font("xx",Font.PLAIN,20));
this.add(center,BorderLayout.CENTER); //输入框放中间
}
public void southPanel(){
Panel south = new Panel(); //创建南边的Panel
TextField tf = new TextField(15); //创建文本字段存储IP地址
Button send = new Button("发送"); //创建发送按钮
Button log = new Button("记录"); //创建记录按钮
Button clear = new Button("清屏"); //创建清屏按钮
Button shake = new Button("震动"); //创建震动按钮
south.add(tf);
south.add(send);
south.add(log);
south.add(clear);
south.add(shake);
this.add(south,BorderLayout.SOUTH); //将Paneal放在fream的南边
}
public void init() {
this.setLocation(500,50);
this.setSize(400,600);
this.setVisible(true);
}
public static void main(String[] args) {
new Demo4_GUIChat();
}
}
UDP聊天发送功能
package com.heima.socket;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Code by pureqh on 2021-03-22
*/
public class Demo4_GUIChat extends Frame {
private TextField tf;
private Button send;
private Button log;
private Button shake;
private Button clear;
private TextArea viewText;
private TextArea sendText;
private DatagramSocket socket;
public Demo4_GUIChat() throws SocketException {
init();
southPanel();
centerPanel();
event();
}
public void event() {
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
socket.close();
System.exit(0);
}
});
send.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
send();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
});
}
private void send() throws IOException {
String message = sendText.getText(); //获取发送区域的内容
String ip = tf.getText(); //获取IP地址
//随机端口号
DatagramPacket packet = new DatagramPacket(message.getBytes(),message.getBytes().length, InetAddress.getByName(ip),9999);
socket.send(packet); //发送数据
String time = getCurrentTime();
viewText.append(time + "我对:" + ip + "说" + "\r\n" + message + "\r\n" + "\r\n"); //将信息添加到显示区域中
sendText.setText("");
}
private String getCurrentTime() {
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
return sdf.format(d); //将时间格式化
}
public void centerPanel() {
Panel center = new Panel();
//显示的文本区域
viewText = new TextArea();
//发送的文本区域
sendText = new TextArea(5,1);
center.setLayout(new BorderLayout()); //设置为边界布局管理器
center.add(sendText, BorderLayout.SOUTH); //发送的文本区域放在南边
center.add(viewText,BorderLayout.CENTER); //显示区域放在中间
viewText.setEditable(false); //设置不可以编辑
viewText.setBackground(Color.white); //设置背景颜色
sendText.setFont(new Font("xx",Font.PLAIN,15)); //设置发送区域字体大小
viewText.setFont(new Font("xx",Font.PLAIN,15));
this.add(center,BorderLayout.CENTER); //输入框放中间
}
public void southPanel(){
Panel south = new Panel(); //创建南边的Panel
//创建文本字段存储IP地址
tf = new TextField(15);
tf.setText("127.0.0.1");
//创建发送按钮
send = new Button("发送");
//创建记录按钮
log = new Button("记录");
//创建清屏按钮
clear = new Button("清屏");
//创建震动按钮
shake = new Button("震动");
south.add(tf);
south.add(send);
south.add(log);
south.add(clear);
south.add(shake);
this.add(south,BorderLayout.SOUTH); //将Paneal放在fream的南边
}
public void init() throws SocketException {
this.setLocation(500,50);
this.setSize(400,600);
new Receive().start();
socket = new DatagramSocket();
this.setVisible(true);
}
private class Receive extends Thread{
public void run(){
//接收和发送需要同时执行,所以要定义成多线程的
try {
DatagramSocket socket = new DatagramSocket(9999);
DatagramPacket packet = new DatagramPacket(new byte[8192],8192);
while (true) {
socket.receive(packet); //接收信息
byte[] arr = packet.getData(); //获取字节数据
int len = packet.getLength(); //获取有效的字节数据
String message = new String(arr, 0, len); //转换成字符串
String time = getCurrentTime(); //获取当前时间
String ip = packet.getAddress().getHostAddress();
viewText.append(time + " " + ip + "对我说:\r\n" + message + "\r\n\r\n");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws SocketException {
new Demo4_GUIChat();
}
}
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Code by pureqh on 2021-03-22
*/
public class Demo4_GUIChat extends Frame {
private TextField tf;
private Button send;
private Button log;
private Button shake;
private Button clear;
private TextArea viewText;
private TextArea sendText;
private DatagramSocket socket;
public Demo4_GUIChat() throws SocketException {
init();
southPanel();
centerPanel();
event();
}
public void event() {
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
socket.close();
System.exit(0);
}
});
send.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
send();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
});
}
private void send() throws IOException {
String message = sendText.getText(); //获取发送区域的内容
String ip = tf.getText(); //获取IP地址
//随机端口号
DatagramPacket packet = new DatagramPacket(message.getBytes(),message.getBytes().length, InetAddress.getByName(ip),9999);
socket.send(packet); //发送数据
String time = getCurrentTime();
viewText.append(time + "我对:" + ip + "说" + "\r\n" + message + "\r\n" + "\r\n"); //将信息添加到显示区域中
sendText.setText("");
}
private String getCurrentTime() {
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
return sdf.format(d); //将时间格式化
}
public void centerPanel() {
Panel center = new Panel();
//显示的文本区域
viewText = new TextArea();
//发送的文本区域
sendText = new TextArea(5,1);
center.setLayout(new BorderLayout()); //设置为边界布局管理器
center.add(sendText, BorderLayout.SOUTH); //发送的文本区域放在南边
center.add(viewText,BorderLayout.CENTER); //显示区域放在中间
viewText.setEditable(false); //设置不可以编辑
viewText.setBackground(Color.white); //设置背景颜色
sendText.setFont(new Font("xx",Font.PLAIN,15)); //设置发送区域字体大小
viewText.setFont(new Font("xx",Font.PLAIN,15));
this.add(center,BorderLayout.CENTER); //输入框放中间
}
public void southPanel(){
Panel south = new Panel(); //创建南边的Panel
//创建文本字段存储IP地址
tf = new TextField(15);
tf.setText("127.0.0.1");
//创建发送按钮
send = new Button("发送");
//创建记录按钮
log = new Button("记录");
//创建清屏按钮
clear = new Button("清屏");
//创建震动按钮
shake = new Button("震动");
south.add(tf);
south.add(send);
south.add(log);
south.add(clear);
south.add(shake);
this.add(south,BorderLayout.SOUTH); //将Paneal放在fream的南边
}
public void init() throws SocketException {
this.setLocation(500,50);
this.setSize(400,600);
new Receive().start();
socket = new DatagramSocket();
this.setVisible(true);
}
private class Receive extends Thread{
public void run(){
//接收和发送需要同时执行,所以要定义成多线程的
try {
DatagramSocket socket = new DatagramSocket(9999);
DatagramPacket packet = new DatagramPacket(new byte[8192],8192);
while (true) {
socket.receive(packet); //接收信息
byte[] arr = packet.getData(); //获取字节数据
int len = packet.getLength(); //获取有效的字节数据
String message = new String(arr, 0, len); //转换成字符串
String time = getCurrentTime(); //获取当前时间
String ip = packet.getAddress().getHostAddress();
viewText.append(time + " " + ip + "对我说:\r\n" + message + "\r\n\r\n");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws SocketException {
new Demo4_GUIChat();
}
}
完善功能
package com.heima.socket;
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Code by pureqh on 2021-03-22
*/
public class Demo4_GUIChat extends Frame {
private TextField tf;
private Button send;
private Button log;
private Button shake;
private Button clear;
private TextArea viewText;
private TextArea sendText;
private DatagramSocket socket;
private BufferedWriter bw;
private String str;
public Demo4_GUIChat() throws IOException {
init();
southPanel();
centerPanel();
event();
}
public void event() {
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
socket.close();
try {
bw.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
System.exit(0);
}
});
send.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
send();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
});
log.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
logFile();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
});
clear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
viewText.setText("");
}
});
shake.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
send(new byte[] {-1},tf.getText());
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
});
sendText.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER ){
try {
send();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
});
}
private void shake() throws InterruptedException {
int x = this.getLocation().x; //获取x坐标位置
int y = this.getLocation().y; //获取x坐标位置
for (int i=0;i<3;i++) {
this.setLocation(x + 5, y + 5);
Thread.sleep(20);
this.setLocation(x + 5, y - 5);
Thread.sleep(20);
this.setLocation(x - 5, y + 5);
Thread.sleep(20);
this.setLocation(x - 5, y + 5);
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 len;
byte[] arr = new byte[8192];
while ((len = fis.read(arr)) != -1){
baos.write(arr,0,len);
}
String str = baos.toString(); //将内存中的内容转换成字符串
viewText.setText(str);
fis.close();
}
private void send(byte[] arr,String ip) throws IOException {
DatagramPacket packet = new DatagramPacket(arr,arr.length, InetAddress.getByName(ip),9999);
socket.send(packet); //发送数据
}
private void send() throws IOException {
String message = sendText.getText(); //获取发送区域的内容
String ip = tf.getText(); //获取IP地址
//随机端口号
DatagramPacket packet = new DatagramPacket(message.getBytes(),message.getBytes().length, InetAddress.getByName(ip),9999);
socket.send(packet); //发送数据
String time = getCurrentTime();
str = time + "我对:" + ip + "说" + "\r\n" + message + "\r\n" + "\r\n";
viewText.append(str); //将信息添加到显示区域中
bw.write(str); //将信息写到数据库中
sendText.setText("");
}
private String getCurrentTime() {
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
return sdf.format(d); //将时间格式化
}
public void centerPanel() {
Panel center = new Panel();
//显示的文本区域
viewText = new TextArea();
//发送的文本区域
sendText = new TextArea(5,1);
center.setLayout(new BorderLayout()); //设置为边界布局管理器
center.add(sendText, BorderLayout.SOUTH); //发送的文本区域放在南边
center.add(viewText,BorderLayout.CENTER); //显示区域放在中间
viewText.setEditable(false); //设置不可以编辑
viewText.setBackground(Color.white); //设置背景颜色
sendText.setFont(new Font("xx",Font.PLAIN,15)); //设置发送区域字体大小
viewText.setFont(new Font("xx",Font.PLAIN,15));
this.add(center,BorderLayout.CENTER); //输入框放中间
}
public void southPanel(){
Panel south = new Panel(); //创建南边的Panel
//创建文本字段存储IP地址
tf = new TextField(15);
tf.setText("127.0.0.1");
//创建发送按钮
send = new Button("发送");
//创建记录按钮
log = new Button("记录");
//创建清屏按钮
clear = new Button("清屏");
//创建震动按钮
shake = new Button("震动");
south.add(tf);
south.add(send);
south.add(log);
south.add(clear);
south.add(shake);
this.add(south,BorderLayout.SOUTH); //将Paneal放在fream的南边
}
public void init() throws IOException {
this.setLocation(500,50);
this.setSize(400,600);
new Receive().start();
socket = new DatagramSocket();
bw = new BufferedWriter(new FileWriter("config.txt",true)); //需要在尾部追加
this.setVisible(true);
}
private class Receive extends Thread{
private String str;
public void run(){
//接收和发送需要同时执行,所以要定义成多线程的
try {
DatagramSocket socket = new DatagramSocket(9999);
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){ //如果发过来的数组第一个存储的值是-1并且数组长度是1
shake();
continue; //终止本次循环,继续下次循环,因为震动后不需要执行下面的代码
}
String message = new String(arr, 0, len); //转换成字符串
String time = getCurrentTime(); //获取当前时间
String ip = packet.getAddress().getHostAddress();
str = time + " " + ip + "对我说:\r\n" + message + "\r\n\r\n";
viewText.append(str);
bw.write(str);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
new Demo4_GUIChat();
}
}
import javax.swing.border.Border;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Code by pureqh on 2021-03-22
*/
public class Demo4_GUIChat extends Frame {
private TextField tf;
private Button send;
private Button log;
private Button shake;
private Button clear;
private TextArea viewText;
private TextArea sendText;
private DatagramSocket socket;
private BufferedWriter bw;
private String str;
public Demo4_GUIChat() throws IOException {
init();
southPanel();
centerPanel();
event();
}
public void event() {
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
socket.close();
try {
bw.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
System.exit(0);
}
});
send.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
send();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
});
log.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
logFile();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
});
clear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
viewText.setText("");
}
});
shake.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
send(new byte[] {-1},tf.getText());
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
});
sendText.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER ){
try {
send();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
});
}
private void shake() throws InterruptedException {
int x = this.getLocation().x; //获取x坐标位置
int y = this.getLocation().y; //获取x坐标位置
for (int i=0;i<3;i++) {
this.setLocation(x + 5, y + 5);
Thread.sleep(20);
this.setLocation(x + 5, y - 5);
Thread.sleep(20);
this.setLocation(x - 5, y + 5);
Thread.sleep(20);
this.setLocation(x - 5, y + 5);
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 len;
byte[] arr = new byte[8192];
while ((len = fis.read(arr)) != -1){
baos.write(arr,0,len);
}
String str = baos.toString(); //将内存中的内容转换成字符串
viewText.setText(str);
fis.close();
}
private void send(byte[] arr,String ip) throws IOException {
DatagramPacket packet = new DatagramPacket(arr,arr.length, InetAddress.getByName(ip),9999);
socket.send(packet); //发送数据
}
private void send() throws IOException {
String message = sendText.getText(); //获取发送区域的内容
String ip = tf.getText(); //获取IP地址
//随机端口号
DatagramPacket packet = new DatagramPacket(message.getBytes(),message.getBytes().length, InetAddress.getByName(ip),9999);
socket.send(packet); //发送数据
String time = getCurrentTime();
str = time + "我对:" + ip + "说" + "\r\n" + message + "\r\n" + "\r\n";
viewText.append(str); //将信息添加到显示区域中
bw.write(str); //将信息写到数据库中
sendText.setText("");
}
private String getCurrentTime() {
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH:mm:ss");
return sdf.format(d); //将时间格式化
}
public void centerPanel() {
Panel center = new Panel();
//显示的文本区域
viewText = new TextArea();
//发送的文本区域
sendText = new TextArea(5,1);
center.setLayout(new BorderLayout()); //设置为边界布局管理器
center.add(sendText, BorderLayout.SOUTH); //发送的文本区域放在南边
center.add(viewText,BorderLayout.CENTER); //显示区域放在中间
viewText.setEditable(false); //设置不可以编辑
viewText.setBackground(Color.white); //设置背景颜色
sendText.setFont(new Font("xx",Font.PLAIN,15)); //设置发送区域字体大小
viewText.setFont(new Font("xx",Font.PLAIN,15));
this.add(center,BorderLayout.CENTER); //输入框放中间
}
public void southPanel(){
Panel south = new Panel(); //创建南边的Panel
//创建文本字段存储IP地址
tf = new TextField(15);
tf.setText("127.0.0.1");
//创建发送按钮
send = new Button("发送");
//创建记录按钮
log = new Button("记录");
//创建清屏按钮
clear = new Button("清屏");
//创建震动按钮
shake = new Button("震动");
south.add(tf);
south.add(send);
south.add(log);
south.add(clear);
south.add(shake);
this.add(south,BorderLayout.SOUTH); //将Paneal放在fream的南边
}
public void init() throws IOException {
this.setLocation(500,50);
this.setSize(400,600);
new Receive().start();
socket = new DatagramSocket();
bw = new BufferedWriter(new FileWriter("config.txt",true)); //需要在尾部追加
this.setVisible(true);
}
private class Receive extends Thread{
private String str;
public void run(){
//接收和发送需要同时执行,所以要定义成多线程的
try {
DatagramSocket socket = new DatagramSocket(9999);
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){ //如果发过来的数组第一个存储的值是-1并且数组长度是1
shake();
continue; //终止本次循环,继续下次循环,因为震动后不需要执行下面的代码
}
String message = new String(arr, 0, len); //转换成字符串
String time = getCurrentTime(); //获取当前时间
String ip = packet.getAddress().getHostAddress();
str = time + " " + ip + "对我说:\r\n" + message + "\r\n\r\n";
viewText.append(str);
bw.write(str);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
new Demo4_GUIChat();
}
}
TCP协议
package com.heima.tcp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* Code by pureqh on 2021-03-24
*/
public class Demo1_Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",12345);
InputStream is = socket.getInputStream(); //获取客户端输入流
OutputStream os = socket.getOutputStream(); //获取客户端输出流
byte[] arr = new byte[1024];
int len = is.read(arr); //读取服务器发来的数据
System.out.println(new String(arr,0,len)); //将数据转换成字符串并打印
os.write("学习挖掘机哪家强".getBytes()); //客户端向服务器写数据
os.close();
}
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* Code by pureqh on 2021-03-24
*/
public class Demo1_Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",12345);
InputStream is = socket.getInputStream(); //获取客户端输入流
OutputStream os = socket.getOutputStream(); //获取客户端输出流
byte[] arr = new byte[1024];
int len = is.read(arr); //读取服务器发来的数据
System.out.println(new String(arr,0,len)); //将数据转换成字符串并打印
os.write("学习挖掘机哪家强".getBytes()); //客户端向服务器写数据
os.close();
}
}
package com.heima.tcp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Code by pureqh on 2021-03-24
*/
public class Demo1_Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(12345);
Socket socket = server.accept(); //接受客户端的请求
InputStream is = socket.getInputStream(); //获取客户端输入流
OutputStream os = socket.getOutputStream(); //获取客户端输出流
os.write("百度一下你就知道".getBytes()); //服务器向客户端写出数据
byte[] arr = new byte[1024];
int len = is.read(arr); //读取客户端发来的数据
System.out.println(new String(arr,0,len)); //将数据转换成字符串并打印
}
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Code by pureqh on 2021-03-24
*/
public class Demo1_Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(12345);
Socket socket = server.accept(); //接受客户端的请求
InputStream is = socket.getInputStream(); //获取客户端输入流
OutputStream os = socket.getOutputStream(); //获取客户端输出流
os.write("百度一下你就知道".getBytes()); //服务器向客户端写出数据
byte[] arr = new byte[1024];
int len = is.read(arr); //读取客户端发来的数据
System.out.println(new String(arr,0,len)); //将数据转换成字符串并打印
}
}
TCP协议代码优化(读入读出均为字符串)
package com.heima.tcp;
import java.io.*;
import java.net.Socket;
/**
* Code by pureqh on 2021-03-24
*/
public class Demo2_Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",12345);
//将字节流包装成字符流
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream()); //printstream中有换行的方法
System.out.println(br.readLine());
ps.println("我想报名黑马程序员");
System.out.println(br.readLine());
ps.println("能不能给次机会");
socket.close();
}
}
import java.io.*;
import java.net.Socket;
/**
* Code by pureqh on 2021-03-24
*/
public class Demo2_Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",12345);
//将字节流包装成字符流
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream()); //printstream中有换行的方法
System.out.println(br.readLine());
ps.println("我想报名黑马程序员");
System.out.println(br.readLine());
ps.println("能不能给次机会");
socket.close();
}
}
package com.heima.tcp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Code by pureqh on 2021-03-24
*/
public class Demo2_Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(12345);
Socket socket = server.accept(); //接受客户端的请求
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());
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Code by pureqh on 2021-03-24
*/
public class Demo2_Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(12345);
Socket socket = server.accept(); //接受客户端的请求
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());
}
}
服务端是多线程的
package com.heima.tcp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Code by pureqh on 2021-03-24
*/
public class Demo2_Server {
public static void main(String[] args) throws IOException {
//demo1();
final ServerSocket server = new ServerSocket(12345);
while (true){
Socket socket = server.accept(); //接受客户端的请求
new Thread(){
public void run(){
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
PrintStream ps = null;
try {
ps = new PrintStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
ps.println("欢迎咨询黑马程序员");
try {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
ps.println("不好意思人满了");
try {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
private static void demo1() throws IOException {
ServerSocket server = new ServerSocket(12345);
Socket socket = server.accept(); //接受客户端的请求
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());
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Code by pureqh on 2021-03-24
*/
public class Demo2_Server {
public static void main(String[] args) throws IOException {
//demo1();
final ServerSocket server = new ServerSocket(12345);
while (true){
Socket socket = server.accept(); //接受客户端的请求
new Thread(){
public void run(){
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
PrintStream ps = null;
try {
ps = new PrintStream(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
ps.println("欢迎咨询黑马程序员");
try {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
ps.println("不好意思人满了");
try {
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
private static void demo1() throws IOException {
ServerSocket server = new ServerSocket(12345);
Socket socket = server.accept(); //接受客户端的请求
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());
}
}
练习1将字符串反转并返回
package com.heima.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
/**
* Code by pureqh on 2021-03-25
*/
public class Test1_Client {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in); //创建键盘录入对象
Socket socket = new Socket("127.0.0.1",30000); //
//获取输入流
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();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;
/**
* Code by pureqh on 2021-03-25
*/
public class Test1_Client {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in); //创建键盘录入对象
Socket socket = new Socket("127.0.0.1",30000); //
//获取输入流
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 com.heima.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;
/**
* Code by pureqh on 2021-03-25
*/
public class Test2_Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(30000);
System.out.println("服务器启动,绑定30000端口");
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();
}
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Code by pureqh on 2021-03-25
*/
public class Test2_Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(30000);
System.out.println("服务器启动,绑定30000端口");
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();
}
}
}
练习2向服务器上传文件
package com.heima.test;
import com.sun.org.apache.bcel.internal.generic.GETFIELD;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
/**
* Code by pureqh on 2021-03-25
*/
public class Test2_UpdateClient {
public static void main(String[] args) throws IOException {
//提示输入要上传的文件路径,验证路径是否存在以及是否是文件夹
File file = getfile();
//发送文件名到服务端
Socket socket = new Socket("127.0.0.1",12345);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println(file.getName());
//接收结果,如果存在给予提示,程序直接退出
String result = br.readLine(); //读取存在或不存在的结果
if ("存在".equals(result)){
System.out.println("您上传的文件已存在,请不要重复上传");
socket.close();
return;
}
//如果不存在,定义fileinputstream读取文件,写出到网络
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();
}
private static File getfile() {
Scanner sc = new Scanner(System.in); //创建键盘录入对象
System.out.println("请输入一个文件路径");
while (true){
String line = sc.nextLine();
File file = new File(line);
if (!file.exists()){
System.out.println("您录入的文件路径不存在,请重新录入");
}else if (file.isDirectory()){
System.out.println("您录入的是文件夹路径,请输入一个文件路径");
}else{
return file;
}
}
}
}
import com.sun.org.apache.bcel.internal.generic.GETFIELD;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
/**
* Code by pureqh on 2021-03-25
*/
public class Test2_UpdateClient {
public static void main(String[] args) throws IOException {
//提示输入要上传的文件路径,验证路径是否存在以及是否是文件夹
File file = getfile();
//发送文件名到服务端
Socket socket = new Socket("127.0.0.1",12345);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println(file.getName());
//接收结果,如果存在给予提示,程序直接退出
String result = br.readLine(); //读取存在或不存在的结果
if ("存在".equals(result)){
System.out.println("您上传的文件已存在,请不要重复上传");
socket.close();
return;
}
//如果不存在,定义fileinputstream读取文件,写出到网络
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();
}
private static File getfile() {
Scanner sc = new Scanner(System.in); //创建键盘录入对象
System.out.println("请输入一个文件路径");
while (true){
String line = sc.nextLine();
File file = new File(line);
if (!file.exists()){
System.out.println("您录入的文件路径不存在,请重新录入");
}else if (file.isDirectory()){
System.out.println("您录入的是文件夹路径,请输入一个文件路径");
}else{
return file;
}
}
}
}
package com.heima.test;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Code by pureqh on 2021-03-25
*/
public class Test2_UpdateServer {
private static InputStream is;
public static void main(String[] args) throws IOException {
//建立多线程的服务器
int port = 12345;
final ServerSocket server = new ServerSocket(port);
System.out.println("服务器启动,绑定"+port +"端口号");
//读取文件名
while (true){
Socket socket = server.accept();
new Thread(){
public void run(){
try {
is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
PrintStream ps = new PrintStream(socket.getOutputStream());
String filename = br.readLine();
//判断文件是否存在,将结果返回客户端
File dir = new File("update");
dir.mkdir(); //创建文件夹
File file = new File(dir,filename); //封装成file对象
if (file.exists()){ //如果服务器存在该文件,将存在写给客户端
ps.println("存在");
socket.close(); //关闭socket
return;
}else {
ps.println("不存在");
}
//定义fileoutputstream,从网络读取数据,存储到本地
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();
}
}
}
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Code by pureqh on 2021-03-25
*/
public class Test2_UpdateServer {
private static InputStream is;
public static void main(String[] args) throws IOException {
//建立多线程的服务器
int port = 12345;
final ServerSocket server = new ServerSocket(port);
System.out.println("服务器启动,绑定"+port +"端口号");
//读取文件名
while (true){
Socket socket = server.accept();
new Thread(){
public void run(){
try {
is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
PrintStream ps = new PrintStream(socket.getOutputStream());
String filename = br.readLine();
//判断文件是否存在,将结果返回客户端
File dir = new File("update");
dir.mkdir(); //创建文件夹
File file = new File(dir,filename); //封装成file对象
if (file.exists()){ //如果服务器存在该文件,将存在写给客户端
ps.println("存在");
socket.close(); //关闭socket
return;
}else {
ps.println("不存在");
}
//定义fileoutputstream,从网络读取数据,存储到本地
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();
}
}
}