一个简单的Demo,使用socket访问指定ip地址的指定端口进行数据读写
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketDemo {
private static final String SERVER_NAME = "";//服务器IP地址
private static final int PORT_NUM = 8081;//服务器端口
private static final int TIME_OUT = 2000;//设置超时时间
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket();
socket.connect(new InetSocketAddress(SERVER_NAME, PORT_NUM), TIME_OUT);//建立连接,设置连接超时时间
socket.setSoTimeout(TIME_OUT);//设置读写超时时间
//打印连接信息
System.out.println("Connected to " + socket.getInetAddress()
+ " on port " + socket.getPort()
+ " from port" + socket.getLocalPort()
+ " of " + socket.getLocalAddress());
//获取读写操作对象
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String phone = "10086";
String password = "123456";
//使用通用的"\r\n",并且及时刷缓冲区
writer.write(phone + "\r\n");
writer.flush();
writer.write(password + "\r\n");
writer.flush();
//读取消息直到连接关闭
String result = null;
while((result = reader.readLine()) != null){
System.out.println(result);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
System.out.println("连接失败");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("读写错误");
e.printStackTrace();
}finally {
if(socket != null){
try {
socket.close();
} catch (IOException e) {
//ignore
}
}
}
System.out.println("连接结束");
}
}