Java基礎(chǔ)筆記總結(jié)(18)-網(wǎng)絡(luò)編程 TCP UDP 聊天小程序

網(wǎng)絡(luò)編程:

每臺(tái)設(shè)備在網(wǎng)絡(luò)中具有唯一的表示,每臺(tái)網(wǎng)絡(luò)終端在網(wǎng)絡(luò)中具有獨(dú)立的地址,網(wǎng)絡(luò)數(shù)據(jù)傳輸就是用改地址

ipconfig

ping

本地回路地址

廣播地址

端口號(hào):

每個(gè)網(wǎng)絡(luò)程序需要綁定端口號(hào),盡量使用1024以上的

mysql 3306

oracle 1521

web 80

tomcat 8080

qq 4000

feiQ2425

協(xié)議:為計(jì)算機(jī)網(wǎng)絡(luò)中進(jìn)行數(shù)據(jù)交換而建立的規(guī)則,標(biāo)準(zhǔn)或約定的集合

UDP 面向無連接 數(shù)據(jù)不安全,速度快,不區(qū)分客戶端與服務(wù)端

TCP 面向連接(三次握手),數(shù)據(jù)安全,速度略低,分為客戶端和服務(wù)端

三次握手 客戶端向服務(wù)端發(fā)起請(qǐng)求,服務(wù)端響應(yīng)請(qǐng)求,傳輸數(shù)據(jù)

-----------------------------------------------------------------------------------------UDP通信

String str="What are you doing now?";

//? ? ? 創(chuàng)建Socket 相當(dāng)于創(chuàng)建碼頭

DatagramSocket socket = new DatagramSocket();

// 創(chuàng)建Packet 相當(dāng)于集裝箱

DatagramPacket packet = new DatagramPacket(str.getBytes(),str.getBytes().length, InetAddress.getByName("127.0.0.1"),6666);

// 發(fā)貨,將數(shù)據(jù)發(fā)出

socket.send(packet);

// 關(guān)閉碼頭

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通信優(yōu)化

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);

// 接受客戶端請(qǐng)求

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("我想報(bào)名黑馬程序員");

socket.close();

/*// 獲取客戶端輸入流

InputStream is = socket.getInputStream();

// 獲取客戶端輸出流

OutputStream os = socket.getOutputStream();

byte[] arr = new byte[1024];

int len = is.read(arr); //讀取服務(wù)器發(fā)送數(shù)據(jù)

System.out.println(new String(arr,0,len));

os.write("學(xué)習(xí)挖掘機(jī)哪家強(qiáng)".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);

// 接受客戶端請(qǐng)求

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();//獲取發(fā)送區(qū)域內(nèi)容

String ip = tf.getText();

ip = ip.trim()==""?"255.255.255.255":ip;

Send(message.getBytes(),ip);

String time = getCurrentTime();

String str = time+" 我對(duì)"+ip+"說"+"\r\n"+message+"\r\n";

bw.write(str);

viewText.append(str);

sendText.setText("");

}

private void logFile() throws IOException {

// 刷新緩沖區(qū)

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("發(fā)送");

btn_log = new Button("記錄");

btn_clear = new Button("清除");

btn_shake = new Button("震動(dòng)");

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()+"對(duì)我說"+"\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();

}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 7.2 面向套接字編程我們已經(jīng)通過了解Socket的接口,知其所以然,下面我們就將通過具體的案例,來熟悉Socke...
    lucas777閱讀 1,273評(píng)論 0 2
  • 一、基礎(chǔ)知識(shí):1、JVM、JRE和JDK的區(qū)別:JVM(Java Virtual Machine):java虛擬機(jī)...
    殺小賊閱讀 2,559評(píng)論 0 4
  • package net; import java.io.BufferedReader; import java.i...
    自由主義者閱讀 586評(píng)論 0 0
  • 引言:網(wǎng)絡(luò)編程作為開發(fā)服務(wù)端和客戶端必不可少的技術(shù)之一,在Java中也實(shí)現(xiàn)的十分完備,今天對(duì)Java的網(wǎng)絡(luò)編程方面...
    cp_insist閱讀 422評(píng)論 0 0
  • 今天是7月5日,星期三,晴。 今天又輪到我們班執(zhí)勤,今天是我們班最后一次執(zhí)勤,大寶早早的就告訴我一定要去執(zhí)勤,我說...
    fba947bf0ca5閱讀 126評(píng)論 1 1

友情鏈接更多精彩內(nèi)容