網(wǎng)絡(luò)通信荐绝,現(xiàn)在隨處可見挂疆,任何東西不涉及網(wǎng)絡(luò)的話漫拭,就感覺少了條手臂亚兄,斷了個腿一樣,今天就來聊聊網(wǎng)絡(luò)通信采驻;
下面來看看socket的原理:
- 基于TCP的Socket編程
下面來看看例子:
Server
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
//服務(wù)器類
public class Server {
public static void main(String[] args) throws Exception {
// 實例化一個list,用于保存所有的User
List<User> list = new ArrayList<User>();
// 創(chuàng)建綁定到特定端口的服務(wù)器套接字
@SuppressWarnings("resource")
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服務(wù)端正在開始~");
// 循環(huán)監(jiān)聽客戶端連接
while (true) {
Socket socket = serverSocket.accept();
// 每接受一個線程审胚,就隨機生成一個一個新用戶
User user = new User("user" + Math.round(Math.random() * 100),socket);
System.out.println(user.getName() + "正在登錄。礼旅。膳叨。");
list.add(user);
// 創(chuàng)建一個新的線程,接收信息并轉(zhuǎn)發(fā)
ServerThread thread = new ServerThread(user, list);
thread.start();
}
}
}
ServerThread
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
/*
* 服務(wù)器線程的作用主要是:
* 1.接收來自客戶端的信息
* 2.將接收到的信息解析痘系,并轉(zhuǎn)發(fā)給目標客戶端
* */
public class ServerThread extends Thread {
private User user;
private List<User> list;
public ServerThread(User user, List<User> list) {
this.user = user;
this.list = list;
}
public void run() {
try {
while (true) {
// 信息的格式:(login||logout||say),發(fā)送人,收發(fā)人,信息體
//不斷地讀取客戶端發(fā)過來的信息
String msg= user.getBr().readLine();
System.out.println(msg);
String[] str = msg.split(",");
switch (str[0]) {
case "logout":
remove(user);// 移除用戶
break;
case "say":
sendToClient(str[1], msg); // 轉(zhuǎn)發(fā)信息給特定的用戶
break;
default:
break;
}
}
} catch (Exception e) {
System.out.println("異常");
} finally {
try {
user.getBr().close();
user.getSocket().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void sendToClient(String username, String msg) {
for (User user : list) {
if (user.getName().equals(username)) {
try {
PrintWriter pw =user.getPw();
pw.println(msg);
pw.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private void remove(User user2) {
list.remove(user2);
}
}
Client
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
/*
* client線程主要是負責:
* 1.發(fā)送信息
* 2.一直接收信息菲嘴,并解析
* */
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 9999);
//開啟一個線程接收信息,并解析
ClientThread thread=new ClientThread(socket);
thread.setName("Client1");
thread.start();
//主線程用來發(fā)送信息
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(socket.getOutputStream());
while(true)
{
String s=br.readLine();
out.println(s);
//out.write(s+"\n");
out.flush();
}
}catch(Exception e){
System.out.println("服務(wù)器異常");
}
}
}
ClientThread
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
/**
* 作用:一直接收服務(wù)端轉(zhuǎn)發(fā)過來的信息
* */
public class ClientThread extends Thread {
private Socket socket;
public ClientThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
InputStream inputStream = socket.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(
inputStream);
BufferedReader br = new BufferedReader(inputStreamReader);
try {
// 信息的格式:(login||logout||say),發(fā)送人,收發(fā)人,信息體
while (true) {
String msg=br.readLine();
System.out.println(msg);
String[] str = msg.split(",");
switch (str[0]) {
case "say":
System.out.println(str[2] + " 對 " + str[1] + " say: "
+ str[3]);
break;
default:
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
User
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class User {
private String name;
private String account;
private Socket socket;
private BufferedReader br;
private PrintWriter pw;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public Socket getSocket() {
return socket;
}
public void setSocket(final Socket socket) {
this.socket = socket;
}
public BufferedReader getBr() {
return br;
}
public void setBr(BufferedReader br) {
this.br = br;
}
public PrintWriter getPw() {
return pw;
}
public void setPw(PrintWriter pw) {
this.pw = pw;
}
public User(String name, final Socket socket) throws IOException {
this.name = name;
this.socket = socket;
this.br = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
this.pw = new PrintWriter(socket.getOutputStream());
}
@Override
public String toString() {
return "User [name=" + name + ", account=" + account + ", socket="
+ socket + "]";
}
}
結(jié)果