Webscoket简单的连接、发送消息和读取服务器返回的消息
#我是刚刚毕业的小白,在公司项目的过程中需要与公司服务器对接socket,模仿写了一个小的简单的socket的工具类,在此写博客是为了加深自己的印象,欢迎各位大神指点,也为同样的小白给出点思路。废话不多说直接贴代码。
public class ScoketUtil {
/**
* ip ip地址
* port 端口
* DataOutputStream 输出流
* DataInputStream 输入流
* */
String ip = "192.168.1.115";
int port = 8001;
DataOutputStream dos = null;
Socket soc = null;
DataInputStream dis = null;
public static String data;
public static void setData(String data) {
ScoketUtil.data = data;
}
/**
* socket 登录
* */
public void Login(){
new Thread(){
@Override
public void run() {
if (soc == null) {
try {
soc = new Socket(ip, port);
//获取socket的输入输出流
dis = new DataInputStream(soc.getInputStream());
dos = new DataOutputStream(soc.getOutputStream());
setData("user login user=admin;password=admin;"); // 这里需要登录用户名和密码所以要发送登录的指令
send();
read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
/**
* 发送消息
* */
public void send(){
new Thread(){
public void run(){
try {
System.out.println(data);
soc.getOutputStream().write(data.getBytes());
soc.getOutputStream().flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
/**
* 读取服务器的返回消息
* */
public void read(){
new Thread(){
public void run(){
while (true){
try {
byte[] b = new byte[1024];
soc.getInputStream().read(b);
System.out.println(new String(b));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
}