客户端socket调用

时间:2023-03-08 21:46:33
 import java.net.Socket;
import java.io.*;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher; class SocketTest
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("please input ipaddress:");
boolean isIp=false;
String strIp="";
//ip正则匹配
Pattern pattern=Pattern.compile("((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))");
while(!isIp){
//System.out.println(isIp);
strIp=sc.next();
Matcher matcher=pattern.matcher(strIp);
//如果输入的数据满足ip格式,继续运行
if(matcher.matches()){
isIp=true;
}
else{
System.out.println("the ip is wrong,please input again:");
}
}
int port=80;
boolean isNu=false;
//如果输入的为正确的端口号(整数)继续运行
while(!isNu){
try{
System.out.println("please input port");
String strPort=sc.next();
port=Integer.parseInt(strPort);
isNu=true;
}catch(Exception ex){
System.out.println("is not int ,please input agein:");
}
} System.out.println("the ip is :"+strIp);
System.out.println("the port is :"+port);
if(strIp!=null&&strIp.length()>0){
try{
//通过ip和端口创建socket实例
Socket socket=new Socket(strIp,port);
//获取socket的输出流
OutputStream outputStream=socket.getOutputStream();
//讲http请求头信息输入至socket输出流中
PrintWriter out=new PrintWriter(outputStream,true);
out.println("GET / HTTP/1.1"); //get 请求,获取目录为/ http协议为http 1.1
out.println("Host: localhost:8888");
out.println("Connection: Close");
out.println();
//接收服务端返回的数据流
BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
boolean loop=true;
StringBuffer sb=new StringBuffer(8096);
while(loop){
if ( in.ready() ) {
int i=0;
while (i!=-1) {
i = in.read();
sb.append((char) i);
}
loop = false;
Thread.currentThread().sleep(50);
}
}
System.out.println(sb.toString());
socket.close();
}
catch (Exception ex) {
ex.printStackTrace();
System.out.println(ex.toString());
}
}
}
}