//网络编程简单的理解就是两台计算机相互通讯数据,Java SDK提供一些相对简单的Api来完成这些工作.Socket就是其中之一,也是用的比较广泛的.
//其他像rmi速度还可以就是只支持java。webservice用的最广泛相对安全和速度略低于socket.废话不说了上代码
/*****
*
* @author skiky
* @describle
*
*/
public class ClientHander {
private final static Integer port = 10001;
private Socket socket = null;
private PrintWriter out = null;
public void sendMessageToService() {
try {
// 获取一个IP。null表示本机
InetAddress addr = InetAddress.getByName(null);
// 开启端口,与服务器建立连接
socket = new Socket(addr, port);
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
for (;;) {
// 向服务器发送信息
Thread.sleep(100 * 5);
// 输出流
out.println("你好 !");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
try {
if (null != out) {
out.close();
}
if (null != socket) {
socket.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public static void main(String[] args) {
new ClientHander().sendMessageToService();
}
}
服务端:
/****
*
* @author skiky
* @describle socket server
*/
public class ServerHander {
private final static Integer port = 10001;
private ServerSocket server = null;
private Socket socket = null;
private BufferedReader in = null;
public void loadServer() {
try {
// create
server = new ServerSocket(port);
// 等待监听是否有客户端连接
socket = server.accept();
// 输入流
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
// 打印接收到的客户端发送过来的信息
for (;;) {
String message = in.readLine();
System.out.println("客户端信息:" + message);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (null != in) {
in.close();
}
if (null != server) {
server.close();
}
if (null != socket) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new ServerHander().loadServer();
}
}
先运行server端再运行client 端,
输出:
客户端信息:你好 !