网络编程:
每台设备在网络中具有唯一的表示,每台网络终端在网络中具有独立的地址,网络数据传输就是用改地址
ipconfig
ping
本地回路地址
广播地址
端口号:
每个网络程序需要绑定端口号,尽量使用1024以上的
mysql 3306
oracle 1521
web 80
tomcat 8080
qq 4000
feiQ2425
协议:为计算机网络中进行数据交换而建立的规则,标准或约定的集合
UDP 面向无连接 数据不安全,速度快,不区分客户端与服务端
TCP 面向连接(三次握手),数据安全,速度略低,分为客户端和服务端
三次握手 客户端向服务端发起请求,服务端响应请求,传输数据
-----------------------------------------------------------------------------------------UDP通信
String str="What are you doing now?";
// 创建Socket 相当于创建码头
DatagramSocket socket = new DatagramSocket();
// 创建Packet 相当于集装箱
DatagramPacket packet = new DatagramPacket(str.getBytes(),str.getBytes().length, InetAddress.getByName("127.0.0.1"),6666);
// 发货,将数据发出
socket.send(packet);
// 关闭码头
socket.close();
DatagramSocket socket = new DatagramSocket(6666);
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
while(true){
socket.receive(packet);
byte[] arr = packet.getData();
int len = packet.getLength();
System.out.println(packet.getAddress().getHostAddress()+":"+packet.getPort()+new String(arr,0,len));
}
-----------------------------------------------------------------------------------------
UDP通信优化
Scanner sc = new Scanner(System.in);
DatagramSocket socket = new DatagramSocket();
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();
DatagramSocket socket = new DatagramSocket(6666);
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
while(true){
socket.receive(packet);
byte[] arr = packet.getData();
int len = packet.getLength();
System.out.println(packet.getAddress().getHostAddress()+":"+packet.getPort()+new String(arr,0,len));
}
-----------------------------------------------------------------------------------
UDP传输多线程
package com.ysu.socket;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;
import javax.print.attribute.standard.DateTimeAtProcessing;
public class UDP_MoreThread {
public static void main(String[] args) {
new Receive().start();
new Send().start();
}
}
class Receive extends Thread {
@Override
public void run() {
try {
DatagramSocket socket = new DatagramSocket(6666);
DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);
while (true) {
socket.receive(packet);
byte[] arr = packet.getData();
int length = packet.getLength();
System.out.println(new String(arr, 0, length));
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Send extends Thread {
@Override
public void run() {
Scanner sc = new Scanner(System.in);
try {
DatagramSocket socket = new DatagramSocket();
while (true) {
String line = sc.nextLine();
if ("quit".equals(line)) {
break;
}
DatagramPacket pocket = new DatagramPacket(line.getBytes(), line.getBytes().length,
InetAddress.getByName("127.0.0.1"), 6666);
socket.send(pocket);
}
socket.close();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
package com.ysu.tcp;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class 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());
socket.close();
/* os.write("百度一下你就知道".getBytes());
byte[] arr = new byte[1024];
int len = is.read(arr);
System.out.println(new String(arr,0,len));
*/socket.close();
}
}
-----------------------------------------------------------------------------------------------------------------------------------------------------------------
package com.ysu.tcp;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
/**
*
* @param args
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("127.0.0.1", 12345);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
System.out.println(br.readLine());
ps.println("我想报名黑马程序员");
socket.close();
/*// 获取客户端输入流
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());
*/
socket.close();
}
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------------
TCP多线程
package com.ysu.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;
public class MoreThreadServer {
public static void main(String[] args) throws IOException {
final ServerSocket server = new ServerSocket(12345);
// 接受客户端请求
while (true) {
new Thread() {
public void run() {
Socket socket;
try {
socket = server.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintStream ps = new PrintStream(socket.getOutputStream());
ps.println("欢迎咨询黑马");
System.out.println(br.readLine());
socket.close();
/*
* os.write("百度一下你就知道".getBytes()); byte[] arr = new
* byte[1024]; int len = is.read(arr);
* System.out.println(new String(arr,0,len));
*/
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
}
}
}
----------------------------------------------------------------------------------------------------------------------------------------------------------------------
聊天程序
package com.ysu.chat;
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.FileNotFoundException;
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 GUIChat extends Frame{
private DatagramSocket socket;
private TextField tf;
private Button btn_send;
private Button btn_clear;
private Button btn_log;
private Button btn_shake;
private TextArea sendText;
private TextArea viewText;
private BufferedWriter bw;
public GUIChat(){
init();
southPanel();
centerPanel();
event();
}
private void event() {
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
try {
bw.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
socket.close();
System.exit(0);
}
});
btn_send.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
Send();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
btn_log.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
logFile();
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
btn_clear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
viewText.setText("");
}
});
btn_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 && e.isControlDown()){
try {
Send();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
});
}
private void shake() {
int x = this.getLocation().x;
int y = this.getLocation().y;
for(int i = 0; i < 20 ; i++){
try {
this.setLocation(x+10, y-10);
Thread.sleep(10);
this.setLocation(x-10, y+10);
Thread.sleep(10);
this.setLocation(x-10, y+10);
Thread.sleep(10);
this.setLocation(x+10, y-10);
Thread.sleep(10);
this.setLocation(x, y);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
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 = ip.trim()==""?"255.255.255.255":ip;
Send(message.getBytes(),ip);
String time = getCurrentTime();
String str = time+" 我对"+ip+"说"+"\r\n"+message+"\r\n";
bw.write(str);
viewText.append(str);
sendText.setText("");
}
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();
}
public String getCurrentTime() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
return sdf.format(date);
}
public void centerPanel() {
Panel center = new Panel();
viewText = new TextArea();
viewText.setEditable(false);
viewText.setBackground(Color.WHITE);
sendText = new TextArea(5,1);
sendText.setFont(new Font("xxx", Font.PLAIN, 20));
viewText.setFont(new Font("xxx", Font.PLAIN, 20));
center.setLayout(new BorderLayout());
center.add(sendText,BorderLayout.SOUTH);
center.add(viewText,BorderLayout.CENTER);
this.add(center,BorderLayout.CENTER);
}
public void southPanel() {
Panel south = new Panel();
tf = new TextField(15);
tf.setText("127.0.0.1");
btn_send = new Button("发送");
btn_log = new Button("记录");
btn_clear = new Button("清除");
btn_shake = new Button("震动");
south.add(tf);
south.add(btn_send);
south.add(btn_log);
south.add(btn_clear);
south.add(btn_shake);
this.add(south,BorderLayout.SOUTH);
}
public void init() {
try {
socket = new DatagramSocket();
try {
bw = new BufferedWriter(new FileWriter("config.txt",true));
} catch (IOException e) {
e.printStackTrace();
}
} catch (SocketException e) {
e.printStackTrace();
}
this.setLocation(500, 50);
this.setSize(400, 600);
this.setVisible(true);
new Receive().start();
}
private class Receive extends Thread{
@Override
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){
shake();
continue;
}
String message = new String(arr,0,len);
String time = getCurrentTime();
String str = time+" "+packet.getAddress().getHostAddress()+"对我说"+"\r\n"+message+"\r\n";
// alt+shift+L 抽取局部变量
bw.write(str);//将信息写到文本文档中
viewText.append(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new GUIChat();
}
}