package com.anin.springboot1.tcpip;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import com.anin.springboot1.test.Test;
/**
- 客户端
- @author Administrator
*/
public class TCPClient {
/**
* socketIP
*/
private static final String SOCKET_IP = "127.0.0.1";
/**
* 端口
*/
private static final int SOCKET_PORT = 6666;
/**
* 连接指定地址和端口socket并获取消息
* 获取完即关闭
* @param args
*/
public static void main(String[] args) {
try {
Socket socket = new Socket(SOCKET_IP,SOCKET_PORT);
System.out.println(Test.getTime()+"连接成功");
InputStream in =socket.getInputStream();
DataInputStream dis = new DataInputStream(in);
System.out.println(Test.getTime()+"获得消息:"+dis.readUTF());
dis.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.anin.springboot1.tcpip;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import com.anin.springboot1.test.Test;
/**
- 服务端
- @author Administrator
*/
public class TCPServer {
/**
* socket端口
*/
private static final int SOCKET_PORT = 6666;
/**
* 设置连接的超时时间
*/
private static final int TIME_OUT = 5000;
private static ServerSocket serversocket = null;
public static void main(String[] args) {
openAndInitSocketServer();
}
/**
* 打开以及初始化socketserver
* 并且向连接该服务端的客户端发送数据
* 发送的数据来源于Test类的doRead方法
* 通过while(true)让服务端一直处于开启状态
* 每一个连接上该服务端的客户端都可以接收到数据
*/
public static void openAndInitSocketServer(){
try {
serversocket = new ServerSocket(SOCKET_PORT);
System.out.println(Test.getTime()+"socket已就绪!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
try {
System.out.println(Test.getTime()+"等待连接");
serversocket.setSoTimeout(TIME_OUT);
//绑定客户端
Socket socket = serversocket.accept();
System.out.println(Test.getTime()+socket.getInetAddress()+"连接成功");
//获取输出流
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
dos.writeUTF(Test.doRead());
dos.close();
socket.close();
} catch (IOException e) {
}
}
}
/**
* 如果socketserver是打开状态
* 即关闭socketserver
*/
public static void closeServer(){
try {
if(serversocket != null){
serversocket.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}