package com.haoran.lesson01; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; //=========在服务器============= public class TcpServerDemo01 { public static void main(String[] args) { ServerSocket serverSocket =null; Socket socket =null; InputStream inputStream =null; ByteArrayOutputStream byteArrayOutputStream =null; try { //建立服务器的端口 serverSocket = new ServerSocket(9999); //等待客户端连接请求 socket = serverSocket.accept(); //读取客户端的输出 inputStream = socket.getInputStream(); //管道流 byteArrayOutputStream = new ByteArrayOutputStream(); byte[] buffer =new byte[1024]; int length; while((length=inputStream.read(buffer))!=-1){ byteArrayOutputStream.write(buffer,0,length); } System.out.println(byteArrayOutputStream.toString()); } catch (IOException e) { e.printStackTrace(); }finally { if(byteArrayOutputStream!=null){ try { byteArrayOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } if(inputStream!=null){ try { inputStream.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(); } } } } }
=================================================
package com.haoran.lesson01;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
//=========在客户端=============
public class TcpClientDemo01 {
public static void main(String[] args) {
Socket socket =null;
OutputStream outputStream =null;
try {
//连接服务器,首先要知道服务器的ip地址以及端口号
InetAddress serverIP = InetAddress.getByName("127.0.0.1");
int port =9999;
//通过ip地址和端口号,创建一个sock类,Socket是应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口。在设计模式中,Socket其实就是一个门面模式,它把复杂的TCP/IP协议族隐藏在Socket接口后面,对用户来说,一组简单的接口就是全部,让Socket去组织数据,以符合指定的协议。
socket = new Socket(serverIP, port);
//发送消息IO流
outputStream = socket.getOutputStream();
outputStream.write("欢迎光临".getBytes());
} catch (Exception e) {
e.printStackTrace();
}finally {
if (outputStream!=null){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}