网络Socket,ServerSocket
//客戶端:
package com.gxnu.study.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
try {
//建立客戶端Socket連接,指定服務器的位置和端口
Socket socket = new Socket("192.168.224.12", 9999);
//打開輸入輸出流
OutputStream os = socket.getOutputStream();
String info = null;
/*
* System.in-->InputStream
* new InputStream(...)把字節流轉化為字符流
*/
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while((info = br.readLine())!=null){
os.write((info+"\n").getBytes());
}
//關閉資源
os.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
?
?
//服務器端
?
package com.gxnu.study.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
try{
//建立一個服務器Socket(ServerSocket)指定端口并開始監聽
ServerSocket serverSocket = new ServerSocket(9999);
//使用accept()方法等待客戶端觸發通信
Socket socket = serverSocket.accept();
//打開輸入輸出流
InputStream is = socket.getInputStream();
//獲取客戶端信息,即從輸入流讀取信息
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String info = null;
while(!((info=br.readLine())==null)){
System.out.println("服務器,客戶信息為:"+info);
}
//關閉資源
br.close();
is.close();
socket.close();
serverSocket.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
轉載于:https://www.cnblogs.com/jiminluo/p/9357319.html
總結
以上是生活随笔為你收集整理的网络Socket,ServerSocket的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: bootstrap3中select2的默
- 下一篇: LVS入门篇(二)之LVS基础