Java網(wǎng)絡編程之基于TCP協(xié)議
一、單向通信
功能:客戶端發(fā)送一句話到服務器:
客戶端:
public class TestClient {//客戶端
//這是一個main方法,是程序的入口:
public static void main(String[] args) throws IOException {
//1.創(chuàng)建套接字:指定服務器的ip和端口號:
Socket s = new Socket("192.168.199.217",8888);
//2.對于程序員來說,向外發(fā)送數(shù)據(jù) 感受 --》利用輸出流:
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
//利用這個OutputStream就可以向外發(fā)送數(shù)據(jù)了,但是沒有直接發(fā)送String的方法
//所以我們又在OutputStream外面套了一個處理流:DataOutputStream
dos.writeUTF("你好");
//3.關閉流 + 關閉網(wǎng)絡資源:
dos.close();
os.close();
s.close();
}
}
服務器端:
public class TestServer {//服務器
//這是一個main方法,是程序的入口:
public static void main(String[] args) throws IOException {
//1.創(chuàng)建套接字: 指定服務器的端口號
ServerSocket ss = new ServerSocket(8888);
//2.等著客戶端發(fā)來的信息:
Socket s = ss.accept();//阻塞方法:等待接收客戶端的數(shù)據(jù),什么時候接收到數(shù)據(jù),什么時候程序繼續(xù)向下執(zhí)行。
//accept()返回值為一個Socket,這個Socket其實就是客戶端的Socket
//接到這個Socket以后,客戶端和服務器才真正產(chǎn)生了連接,才真正可以通信了
//3.感受到的操作流:
InputStream is = s.getInputStream();
DataInputStream dis = new DataInputStream(is);
//4.讀取客戶端發(fā)來的數(shù)據(jù):
String str = dis.readUTF();
System.out.println("客戶端發(fā)來的數(shù)據(jù)為:"+str);
//5.關閉流+關閉網(wǎng)絡資源:
dis.close();
is.close();
s.close();
ss.close();
}
}
測試:
先開啟客戶端還是先開啟服務器:先開服務器,再開啟客戶端 側面驗證:先開客戶端:出錯。
如圖:

二、雙向通信
客戶端:
import java.io.*;
import java.net.Socket;
public class TestClient {//客戶端
//這是一個main方法,是程序的入口:
public static void main(String[] args) throws IOException {
//1.創(chuàng)建套接字:指定服務器的ip和端口號:
Socket s = new Socket("192.168.199.217",8888);
//2.對于程序員來說,向外發(fā)送數(shù)據(jù) 感受 --》利用輸出流:
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
//利用這個OutputStream就可以向外發(fā)送數(shù)據(jù)了,但是沒有直接發(fā)送String的方法
//所以我們又在OutputStream外面套了一個處理流:DataOutputStream
dos.writeUTF("你好");
//接收服務器端的回話--》利用輸入流:
InputStream is = s.getInputStream();
DataInputStream dis = new DataInputStream(is);
String str = dis.readUTF();
System.out.println("服務器端對我說:"+str);
//3.關閉流 + 關閉網(wǎng)絡資源:
dis.close();
is.close();
dos.close();
os.close();
s.close();
}
}
服務器端:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServer {//服務器
//這是一個main方法,是程序的入口:
public static void main(String[] args) throws IOException {
//1.創(chuàng)建套接字: 指定服務器的端口號
ServerSocket ss = new ServerSocket(8888);
//2.等著客戶端發(fā)來的信息:
Socket s = ss.accept();//阻塞方法:等待接收客戶端的數(shù)據(jù),什么時候接收到數(shù)據(jù),什么時候程序繼續(xù)向下執(zhí)行。
//accept()返回值為一個Socket,這個Socket其實就是客戶端的Socket
//接到這個Socket以后,客戶端和服務器才真正產(chǎn)生了連接,才真正可以通信了
//3.感受到的操作流:
InputStream is = s.getInputStream();
DataInputStream dis = new DataInputStream(is);
//4.讀取客戶端發(fā)來的數(shù)據(jù):
String str = dis.readUTF();
System.out.println("客戶端發(fā)來的數(shù)據(jù)為:"+str);
//向客戶端輸出一句話:---》操作流---》輸出流
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("你好,我是服務器端,我接受到你的請求了");
//5.關閉流+關閉網(wǎng)絡資源:
dos.close();
os.close();
dis.close();
is.close();
s.close();
ss.close();
}
}
注意:關閉防火墻
三、對象流傳送
封裝的User類:
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 9050691344308365540L;
private String name;
private String pwd;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public User(String name, String pwd) {
this.name = name;
this.pwd = pwd;
}
}
客戶端:
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class TestClient {//客戶端
//這是一個main方法,是程序的入口:
public static void main(String[] args) throws IOException {
//1.創(chuàng)建套接字:指定服務器的ip和端口號:
Socket s = new Socket("192.168.199.217",8888);
//錄入用戶的賬號和密碼:
Scanner sc = new Scanner(System.in);
System.out.println("請錄入您的賬號:");
String name = sc.next();
System.out.println("請錄入您的密碼:");
String pwd = sc.next();
//將賬號和密碼封裝為一個User的對象:
User user = new User(name,pwd);
//2.對于程序員來說,向外發(fā)送數(shù)據(jù) 感受 --》利用輸出流:
OutputStream os = s.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(user);
//接收服務器端的回話--》利用輸入流:
InputStream is = s.getInputStream();
DataInputStream dis = new DataInputStream(is);
boolean b = dis.readBoolean();
if(b){
System.out.println("恭喜,登錄成功");
}else{
System.out.println("對不起,登錄失敗");
}
//3.關閉流 + 關閉網(wǎng)絡資源:
dis.close();
is.close();
oos.close();
os.close();
s.close();
}
}
服務器:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServer {//服務器
//這是一個main方法,是程序的入口:
public static void main(String[] args) throws IOException, ClassNotFoundException {
//1.創(chuàng)建套接字: 指定服務器的端口號
ServerSocket ss = new ServerSocket(8888);
//2.等著客戶端發(fā)來的信息:
Socket s = ss.accept();//阻塞方法:等待接收客戶端的數(shù)據(jù),什么時候接收到數(shù)據(jù),什么時候程序繼續(xù)向下執(zhí)行。
//accept()返回值為一個Socket,這個Socket其實就是客戶端的Socket
//接到這個Socket以后,客戶端和服務器才真正產(chǎn)生了連接,才真正可以通信了
//3.感受到的操作流:
InputStream is = s.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
//4.讀取客戶端發(fā)來的數(shù)據(jù):
User user = (User)(ois.readObject());
//對對象進行驗證:
boolean flag = false;
if(user.getName().equals("娜娜")&&user.getPwd().equals("123123")){
flag = true;
}
//向客戶端輸出結果:---》操作流---》輸出流
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeBoolean(flag);
//5.關閉流+關閉網(wǎng)絡資源:
dos.close();
os.close();
ois.close();
is.close();
s.close();
ss.close();
}
}
四、加入完整的處理異常方式
服務器端:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServer {//服務器
//這是一個main方法,是程序的入口:
public static void main(String[] args) {
//1.創(chuàng)建套接字: 指定服務器的端口號
ServerSocket ss = null;
Socket s = null;
InputStream is = null;
ObjectInputStream ois = null;
OutputStream os = null;
DataOutputStream dos = null;
try {
ss = new ServerSocket(8888);
//2.等著客戶端發(fā)來的信息:
s = ss.accept();//阻塞方法:等待接收客戶端的數(shù)據(jù),什么時候接收到數(shù)據(jù),什么時候程序繼續(xù)向下執(zhí)行。
//accept()返回值為一個Socket,這個Socket其實就是客戶端的Socket
//接到這個Socket以后,客戶端和服務器才真正產(chǎn)生了連接,才真正可以通信了
//3.感受到的操作流:
is = s.getInputStream();
ois = new ObjectInputStream(is);
//4.讀取客戶端發(fā)來的數(shù)據(jù):
User user = (User)(ois.readObject());
//對對象進行驗證:
boolean flag = false;
if(user.getName().equals("娜娜")&&user.getPwd().equals("123123")){
flag = true;
}
//向客戶端輸出結果:---》操作流---》輸出流
os = s.getOutputStream();
dos = new DataOutputStream(os);
dos.writeBoolean(flag);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
//5.關閉流+關閉網(wǎng)絡資源:
try {
if(dos!=null){
dos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(os!=null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(ois!=null){
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(is!=null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(s!=null){
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(ss!=null){
ss.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
客戶端:
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
public class TestClient {//客戶端
//這是一個main方法,是程序的入口:
public static void main(String[] args){
//1.創(chuàng)建套接字:指定服務器的ip和端口號:
Socket s = null;
OutputStream os = null;
ObjectOutputStream oos = null;
InputStream is = null;
DataInputStream dis = null;
try {
s = new Socket("192.168.199.217",8888);
//錄入用戶的賬號和密碼:
Scanner sc = new Scanner(System.in);
System.out.println("請錄入您的賬號:");
String name = sc.next();
System.out.println("請錄入您的密碼:");
String pwd = sc.next();
//將賬號和密碼封裝為一個User的對象:
User user = new User(name,pwd);
//2.對于程序員來說,向外發(fā)送數(shù)據(jù) 感受 --》利用輸出流:
os = s.getOutputStream();
oos = new ObjectOutputStream(os);
oos.writeObject(user);
//接收服務器端的回話--》利用輸入流:
is = s.getInputStream();
dis = new DataInputStream(is);
boolean b = dis.readBoolean();
if(b){
System.out.println("恭喜,登錄成功");
}else{
System.out.println("對不起,登錄失敗");
}
} catch (IOException e) {
e.printStackTrace();
} finally{
//3.關閉流 + 關閉網(wǎng)絡資源:
try {
if(dis!=null){
dis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(is!=null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(oos!=null){
oos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(os!=null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(s!=null){
s.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
五、多線程接收用戶請求
問題:
- 服務器針對一個請求服務,之后服務器就關閉了(程序自然結束了)
需要解決:
- 服務器必須一直在監(jiān)聽 ,一直開著,等待客戶端的請求
- 在當前代碼中,客戶端不用動了

更改服務器代碼:
服務器線程:
import java.io.*;
import java.net.Socket;
public class ServerThread extends Thread {//線程:專門處理客戶端的請求
InputStream is = null;
ObjectInputStream ois = null;
OutputStream os = null;
DataOutputStream dos = null;
Socket s = null;
public ServerThread(Socket s){
this.s = s;
}
@Override
public void run() {
try{
//2.等著客戶端發(fā)來的信息:
is = s.getInputStream();
ois = new ObjectInputStream(is);
//4.讀取客戶端發(fā)來的數(shù)據(jù):
User user = (User)(ois.readObject());
//對對象進行驗證:
boolean flag = false;
if(user.getName().equals("娜娜")&&user.getPwd().equals("123123")){
flag = true;
}
//向客戶端輸出結果:---》操作流---》輸出流
os = s.getOutputStream();
dos = new DataOutputStream(os);
dos.writeBoolean(flag);
}catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}finally {
try {
if(dos!=null){
dos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(os!=null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(ois!=null){
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if(is!=null){
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
服務器端:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TestServer {//服務器
//這是一個main方法,是程序的入口:
public static void main(String[] args) {
System.out.println("服務器啟動了");
//1.創(chuàng)建套接字: 指定服務器的端口號
ServerSocket ss = null;
Socket s = null;
int count = 0;//定義一個計數(shù)器,用來計數(shù) 客戶端的請求
try {
ss = new ServerSocket(8888);
while(true){//加入死循環(huán),服務器一直監(jiān)聽客戶端是否發(fā)送數(shù)據(jù)
s = ss.accept();//阻塞方法:等待接收客戶端的數(shù)據(jù),什么時候接收到數(shù)據(jù),什么時候程序繼續(xù)向下執(zhí)行。
//每次過來的客戶端的請求 靠 線程處理:
new ServerThread(s).start();
count++;
//輸入請求的客戶端的信息:
System.out.println("當前是第"+count+"個用戶訪問我們的服務器,對應的用戶是:"+s.getInetAddress());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
到此這篇關于Java網(wǎng)絡編程之基于TCP協(xié)議的文章就介紹到這了,更多相關Java基于TCP的網(wǎng)絡編程內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java常用類庫Apache Commons工具類說明及使用實例詳解
這篇文章主要介紹了Java常用類庫Apache Commons工具類說明及使用實例詳解,需要的朋友可以參考下2020-02-02
SpringBoot中實現(xiàn)Redis?Stream隊列的代碼實例
本文介紹了如何在Spring?Boot中使用Redis?Stream隊列進行消息的生產(chǎn)和消費,涉及到的主要內容包括添加Redis依賴、配置RedisTemplate、創(chuàng)建生產(chǎn)者和消費者監(jiān)聽器等,需要的朋友可以參考下2024-09-09
利用Java異常機制實現(xiàn)模擬借書系統(tǒng)
這篇文章主要給大家介紹了利用Java異常機制實現(xiàn)模擬借書系統(tǒng)的相關資料,文中先對java異常機制進行了簡單介紹,而后通過示例代碼介紹了java語言是如何實現(xiàn)一個控制臺版的模擬借書系統(tǒng),需要的朋友可以參考學習,一起來看看吧。2017-04-04
Java concurrency之AtomicLong原子類_動力節(jié)點Java學院整理
AtomicLong是作用是對長整形進行原子操作。下面通過本文給大家介紹Java concurrency之AtomicLong原子類的相關知識,感興趣的朋友一起看看吧2017-06-06
基于@RestControllerAdvice與@ControllerAdvice的區(qū)別說明
這篇文章主要介紹了@RestControllerAdvice與@ControllerAdvice的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09
Spring線程池ThreadPoolTaskExecutor的用法及說明
這篇文章主要介紹了Spring線程池ThreadPoolTaskExecutor的用法及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07

