socket简单小例子
程序员文章站
2022-03-02 12:47:18
...
Client
package socket;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
OutputStream output = null;
BufferedWriter writer = null;
Socket socket = null;
try {
//1.创建socket
socket = new Socket("localhost",9999);
//2.获取输出流
output = socket.getOutputStream();
//3.输出流包装成缓冲流
writer = new BufferedWriter(new OutputStreamWriter(output));
Scanner input = new Scanner(System.in);
System.out.println("start input");
//4.写入到输出流
writer.write(input.next());
//5.刷新数据
writer.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
writer.close();
output.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Server
package socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) {
Socket socket = null;
ServerSocket server = null;
InputStream is = null;
BufferedReader reader = null;
try {
//1.开启监听
server = new ServerSocket(9999);
System.out.println("start listener");
//2.接受客户端传过来的信息
socket = server.accept();
//3.获取输入流
is = socket.getInputStream();
//4.输入流包装成缓冲流
reader = new BufferedReader(new InputStreamReader(is));
//5.读取打印
System.out.println(reader.readLine());
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
is.close();
reader.close();
socket.close();
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}