ClientAndServer
1.Client
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("127.0.0.1",10000);
OutputStream outputStream = socket.getOutputStream();
outputStream.write("你好,服务器,我是客户端".getBytes());
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
int length = inputStream.read(bytes);
System.out.println("服务器说:"+new String(bytes,0,length));
inputStream.close();
outputStream.close();
socket.close();
}
}
2.Server
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(10000);
System.out.println("*************服务器已开启************");
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
int length = inputStream.read(bytes);
System.out.println("客户端说:"+new String(bytes,0,length));
OutputStream outputStream = socket.getOutputStream();
outputStream.write("我是服务器,我已收到你的信息".getBytes());
outputStream.close();
inputStream.close();
socket.close();
serverSocket.close();
}
}
InetAddressDemo
import java.net.InetAddress;
import java.net.UnknownHostException;
public class InetAddressDemo {
public static void main(String[] args) throws UnknownHostException {
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println(inetAddress);
InetAddress address = InetAddress.getByName("www.baidu.com");
System.out.println(address);
System.out.println(address.getHostName());
System.out.println(address.getHostAddress());
}
}