8 TCP字节流编程1
编写一个服务器端和一个客户端
服务器端在9999端口监听
客户端和服务器端各有一个socket
服务端代码
public class SocketTCP01Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服务端,在9999端口监听,等待连接");
Socket socket = serverSocket.accept();
System.out.println("服务端,socket="+socket.getClass());
InputStream inputStream = socket.getInputStream();
byte[] buf=new byte[1024];
int readLen=0;
while ((readLen=inputStream.read(buf))!=-1){
System.out.println(new String(buf,0,readLen));
}
inputStream.close();
socket.close();
serverSocket.close();
}
}
客户端代码
public class SocketTCP01Client {
public static void main(String[] args) throws Exception {
Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
System.out.println("客户端 socket返回"+socket.getClass());
OutputStream outputStream = socket.getOutputStream();
outputStream.write("hello,server".getBytes());
outputStream.close();
socket.close();
System.out.println("客户端退出");
}
}
9 TCP字节流编程2
server端代码
@SuppressWarnings({"all"})
public class SocketTCP02Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
System.out.println("服务端,在9999端口监听,等待连接");
Socket socket = serverSocket.accept();
System.out.println("服务端,socket="+socket.getClass());
InputStream inputStream = socket.getInputStream();
byte[] buf=new byte[1024];
int readLen=0;
while ((readLen=inputStream.read(buf))!=-1){
System.out.println(new String(buf,0,readLen));
}
OutputStream outputStream = socket.getOutputStream();
outputStream.write("hello,client".getBytes());
socket.shutdownOutput();
outputStream.close();
inputStream.close();
socket.close();
serverSocket.close();
}
}
客户端代码
@SuppressWarnings({"all"})
public class SocketTCP02Client {
public static void main(String[] args) throws Exception {
Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
System.out.println("客户端 socket返回"+socket.getClass());
OutputStream outputStream = socket.getOutputStream();
outputStream.write("hello,server".getBytes());
socket.shutdownOutput();
InputStream inputStream = socket.getInputStream();
byte[] buf=new byte[1024];
int readLen=0;
while ((readLen=inputStream.read(buf))!=-1){
System.out.println(new String(buf,0,readLen));
}
inputStream.close();
outputStream.close();
socket.close();
System.out.println("客户端退出");
}
}