Java Socket基本使用

首先 编写Client程序:

 import java.io.IOException;
import java.net.Socket;
import java.util.Scanner; public class Client {
public static void main(String[] args) throws IOException {
/**
* 创建Socket
* 接收服务器端发送数据
*/
Socket socket = new Socket("127.0.0.1", 9999);
Scanner sc = new Scanner(socket.getInputStream());
sc.useDelimiter("\n");
while(sc.hasNext()){
System.out.println(sc.next());
}
sc.close();
socket.close();
}
}

客户端通过多线程发送给客户端数据:

 import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket; class ThreadSocket implements Runnable {
/**
* 线程接收到socket实例后执行run()处理
*/
private Socket socket; public ThreadSocket(Socket socket) {
this.socket = socket;
} @Override
public void run() {
try {
PrintStream printStream = new PrintStream(socket.getOutputStream());
printStream.println("<h1 align='center'>nihao erzhi</h1>");
printStream.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} public class Server {
public static void main(String[] args) throws Exception {
/**
* 创建ServerSocket
*/
ServerSocket server = new ServerSocket(9999);
Socket socket = null;
while (true) {
/**
* 死循环监听端口
* 有消息开一个线程处理
*/
socket = server.accept();
new Thread(new ThreadSocket(socket)).start();
}
}
}
上一篇:关于AndroidSDK配置时的tools目录下找不到adb.exe的错误


下一篇:android 新闻应用、Xposed模块、酷炫的加载动画、下载模块、九宫格控件等源码