接收端- package tcp.communication;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class Receiver {
- /**
- * @param args
- * @throws IOException
- */
- public static void main(String[] args) throws IOException {
- // 建立Socket对象
- ServerSocket ss = new ServerSocket(10086);
- // 监听链接
- System.out.println("监听链接:");
- // 获取输入流
- Socket s = ss.accept();
- while (true) {
- InputStream is = s.getInputStream();
- BufferedReader br = new BufferedReader(new InputStreamReader(is));
- // 解析信息
- // System.out.println("等待消息:");
- String line = br.readLine();
- System.out.println(s.getInetAddress().getHostAddress() + " :"
- + line);
- // 反馈消息
- BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
- s.getOutputStream()));
- bw.write("消息收到!!");
- bw.newLine();
- bw.flush();
- }
- }
- }
复制代码
发送端- package tcp.communication;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.OutputStreamWriter;
- import java.net.Socket;
- import java.net.UnknownHostException;
- public class Sender {
- /**
- * @param args
- * @throws IOException
- * @throws UnknownHostException
- */
- public static void main(String[] args) throws UnknownHostException,
- IOException {
- // 建立套接字对象
- Socket s = new Socket("192.168.31.248", 10086);
- // 获取输入流对象
- InputStream is = s.getInputStream();
- OutputStream os = s.getOutputStream();
- // 封装键盘录入信息
- String message = null;
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- BufferedReader feedback = new BufferedReader(new InputStreamReader(is));
- BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
- while((message = br.readLine())!= null){
- if("886".equals(message))
- break;
- bw.write(message);
- bw.newLine();
- bw.flush();
- System.out.println(s.getInetAddress().getHostAddress()+" ... "+feedback.readLine());
- }
- // 发送信息
- // 释放资源
- os.close();
- }
- }
复制代码 |