java:socket通信
生活随笔
收集整理的這篇文章主要介紹了
java:socket通信
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
基于tcp協(xié)議,建立穩(wěn)定連接的點對點的通信。
? 實時,快速,安全性高,占用系統(tǒng)資源高,效率低
請求-響應(yīng)模式(request, response)
? 客戶端: 在網(wǎng)絡(luò)通訊中,第一次主動發(fā)起通訊的程序叫做客戶端程序。
? 服務(wù)器:第一次通訊中等待連接的程序被稱作服務(wù)器端程序。
?
tcp有點像兩個人打電話,必須電話線接通,兩個人才可以通話。
?
Socket:發(fā)送TCP消息
ServerSocket:創(chuàng)建服務(wù)器
?
package com.test;import java.io.BufferedReader; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket;// 客戶端 public class SocketClient {public static void main(String[] args) throws IOException{Socket client = new Socket("localhost", 8888);client.getOutputStream();// // 輸入 // BufferedReader br = new BufferedReader(new InputStreamReader(client.getInputStream())); // String msg = br.readLine(); // 阻塞式方法 // System.out.println(msg);DataInputStream dis = new DataInputStream(client.getInputStream());String msg = dis.readUTF();System.out.println(msg);} } package com.test;import java.io.BufferedWriter; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket;// 服務(wù)端 public class SocketServer {public static void main(String[] args) throws IOException{// 創(chuàng)建服務(wù)器,指定端口ServerSocket server = new ServerSocket(8888);// 接受客戶端連接, 阻塞式Socket socket = server.accept();System.out.println("一個客戶端建立連接");// 發(fā)送數(shù)據(jù)String msg = "tcp編程";// 輸出流 // BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); // bw.write(msg); // bw.newLine(); // bw.flush();DataOutputStream dos = new DataOutputStream(socket.getOutputStream());dos.writeUTF(msg);dos.flush();} }?
?
?基于Socket,ServerSocket實現(xiàn)類似聊天室的功能
import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List;// 服務(wù)器 public class Server {private List<Channel> channels = new ArrayList<Channel>();public static void main(String[] args) throws IOException{Server s = new Server();s.start();}public void start() throws IOException{ServerSocket server = new ServerSocket(8888);while(true){Socket client = server.accept();Channel n = new Channel(client);channels.add(n);new Thread(n).start();}}private class Channel implements Runnable{private DataInputStream dis;private DataOutputStream dos;private boolean isRunning = true;public Channel(Socket client){try {dis = new DataInputStream(client.getInputStream());dos = new DataOutputStream(client.getOutputStream());} catch (IOException e) {CloseUtil.close(dis,dos);isRunning = false;}}private String recevieMsg(){String msg = "";try {//System.out.println("server..等待讀...");return dis.readUTF();} catch (IOException e) {CloseUtil.close(dis,dos);isRunning = false;}return msg;}private void sendMsg(String msg){// 輸出流try {dos.writeUTF("服務(wù)器-->"+msg);dos.flush();} catch (IOException e) {CloseUtil.close(dis,dos);isRunning = false;}}private void sendMsgToOthers(){// 輸出流try {System.out.println("channels.size() "+channels.size());String msg = recevieMsg();for(Channel n : channels){if(n == this){continue;}System.out.println("recevieMsg() "+msg);n.sendMsg(msg);}} catch (Exception e) {CloseUtil.close(dis,dos);isRunning = false;}}@Overridepublic void run() {while(isRunning){sendMsgToOthers();}}} } import java.io.IOException; import java.net.Socket;// 客戶端 public class Client {public static void main(String[] args) throws IOException{Socket socket = new Socket("localhost", 8888);new Thread(new Send(socket)).start(); // 一條路徑new Thread(new Receive(socket)).start(); // 一條路徑} } import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket;// 發(fā)送 public class Send implements Runnable{// 管道流private BufferedReader br = null;// 輸出流private DataOutputStream dos = null;private boolean isRunning = true;public Send(){br = new BufferedReader(new InputStreamReader(System.in));}public Send(Socket client){this();try {dos = new DataOutputStream(client.getOutputStream());} catch (IOException e) {isRunning = false;CloseUtil.close(dos,br);}}private String getMsgFromConsole(){try {return br.readLine();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "";}private void sendMsg(){String msg = getMsgFromConsole();try {dos.writeUTF(msg);dos.flush(); // 強制刷新} catch (IOException e) {isRunning = false;CloseUtil.close(dos,br);}}@Overridepublic void run() {while(isRunning){sendMsg();}} } import java.io.DataInputStream; import java.io.IOException; import java.net.Socket;// 接收 public class Receive implements Runnable{// 輸出流private DataInputStream dis = null;private boolean isRunning = true;public Receive(){}public Receive(Socket client){try {dis = new DataInputStream(client.getInputStream());} catch (IOException e) {isRunning = false;CloseUtil.close(dis);}}public String readMsg(){String msg = "";try {//System.out.println("readUTF()之前..."+System.currentTimeMillis());msg = dis.readUTF();//System.out.println("readUTF()之后..."+System.currentTimeMillis());return msg;} catch (IOException e) {isRunning = false;CloseUtil.close(dis);}return msg;}@Overridepublic void run() {while(isRunning){System.out.println(readMsg());}} } import java.io.Closeable; import java.io.IOException;public class CloseUtil {public static void close(Closeable...cios){for(Closeable cio : cios){try {if(null != cio){ cio.close();}} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}} }?
總結(jié)
以上是生活随笔為你收集整理的java:socket通信的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java:UDP通信
- 下一篇: java:接口和抽象