01.socket定义
02.TCP编程
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class clientSocket {
public static void main(String[] args) throws IOException {
//创建客户端socket,这个socket链接的ip地址是主机,用Inetaddress来获取,此时是主机,端口号是9999
Socket socket= new Socket(InetAddress.getLocalHost(),9999);
System.out.println("客户端的socket"+socket.getClass());
//获取这个socket的输出流
OutputStream outputStream= socket.getOutputStream();
//输出流输出的写方法
outputStream.write("hello server ".getBytes());
//关闭
outputStream.close();
socket.close();
}
}
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class serverSocket {
public static void main(String[] args) throws IOException {
//在主机创建服务器socket,用于对客户端socket访问进行回复,此时设置的端口号是9999
ServerSocket server=new ServerSocket(9999);
//服务器Serversocket开启监听模式,一旦监听到客户端socket的访问,就会马上返回一个socket到客户端进行通信,这个返回的socket就是变量 声明的这个socket
//等待客户端连接,此方法连接之前一直阻塞
Socket socket= server.accept();
//获取返回的socket的输入流
InputStream inputStream=socket.getInputStream();
//设置读取数据放置的位置,一个比特数组
byte[] readruf=new byte[1024];
//read函数的标识位,这个是inputstream的read函数
int readlen=0;
//具体看inputstream的read函数源码,把数据从输入流中读到byte数组
while((readlen=inputStream.read(readruf))!=-1){
//打印
System.out.println(new String(readruf,0,readlen));
}
inputStream.close();
server.close();、
socket.close();
}
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class clientSocket {
public static void main(String[] args) throws IOException {
//创建客户端socket,这个socket链接的ip地址是主机,用Inetaddress来获取,此时是主机,端口号是9999
Socket socket= new Socket(InetAddress.getLocalHost(),9999);
System.out.println("客户端的socket"+socket.getClass());
//获取socket输出流,写了hello server
OutputStream outputStream= socket.getOutputStream();
outputStream.write("hello server ".getBytes());
//因为来回的都是这个链接(不是socket),需要关闭链接的输出流,互斥的
socket.shutdownOutput();
InputStream inputStream=socket.getInputStream();
byte[] readruf=new byte[1024];
int readlen=0;
while((readlen=inputStream.read(readruf))!=-1){
System.out.println(new String(readruf,0,readlen));
}
inputStream.close();
outputStream.close();
socket.close();
}
}
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class serverSocket {
public static void main(String[] args) throws IOException {
ServerSocket server=new ServerSocket(9999);
Socket socket= server.accept();
InputStream inputStream=socket.getInputStream();
byte[] readruf=new byte[1024];
int readlen=0;
while((readlen=inputStream.read(readruf))!=-1){
System.out.println(new String(readruf,0,readlen));
}
OutputStream outputStream= socket.getOutputStream();
outputStream.write("hello ".getBytes());
socket.shutdownOutput();
outputStream.close();
inputStream.close();
server.close();、
socket.close();
}