什么是 TCP/IP?
TCP/IP 是供已連接因特網的計算機進行通信的通信協議,
TCP/IP 指傳輸控制協議/網際協議 (Transmission Control Protocol / Internet Protocol),
TCP/IP 定義了電子設備(比如計算機)如何連入因特網,以及資料如何在它們之間傳輸的標準,
接下來進行TCP,客戶端以及服務器端的案例演示:
客戶端
1、連接服務器Socket
2、發送訊息
//客戶端
public class TcpClientDemo01 {
public static void main(String[] args) {
Socket socket=null;
OutputStream os=null;
try {
//1、要知道服務器的地址,編口號
InetAddress serverIP=InetAddress.getByName("127.0.0.1");
int port = 9999;
//2、創建一個socket連接
socket=new Socket(serverIP,port);
//3、發送訊息 IO流
os=socket.getOutputStream();
os.write("你好,歡迎來到Java語言!".getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
服務器
1、建立服務的埠 ServerSocket
2、等待用戶的連接 accept
3、接受用戶的訊息
//服務端
public class TcpServerDemo01 {
public static void main(String[] args) {
ServerSocket serverSocket=null;
Socket socket=null;
InputStream is = null;
ByteArrayOutputStream baos=null;
try {
//1、我得有一個地址
serverSocket=new ServerSocket(9999);
while (true){
//2、等待客戶端連接過來
socket=serverSocket.accept();
//3、讀取客戶端的訊息
is =socket.getInputStream();
baos=new ByteArrayOutputStream();
byte[] buffer=new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
baos.write(buffer,0,len);
}
System.out.println(baos.toString());
}
/*
*
* byte[] buffer=new byte[1024];
int len;
while ((len=is.read(buffer))!=-1){
String msg=new String(buffer,0,len);
System.out.println(msg);
}
* */
//管道流
} catch (IOException e) {
e.printStackTrace();
}finally {
//關閉資源
if(baos!=null){
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
注意:先執行服務端,再去執行客戶端

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/274046.html
標籤:java
下一篇:深入理解單例模式與破解單例模式
