/*
* 【需求】客户端和服务端进行交互,类似于QQ聊天形式,互相发送接收信息。
* 图解详见桌面文件26Internet12,客户端out数据对应服务端in数据,服务端out数据对应客户端in数据
*/
package demo;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class ClientDemo {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("10.196.19.56",10002);
OutputStream out = socket.getOutputStream();
out.write("TCP演示......".getBytes());
//读取服务端反馈的数据,使用Socket输入流
InputStream in = socket.getInputStream();//由于是服务端发出的数据,这里需要in进客户端
byte[] buf = new byte[1024];
int len = in.read(buf);
String text = new String(buf,0,len);
System.out.println(text);
socket.close();
}
}
========================分割线=================================
package demo;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerDemo {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(10002);
Socket s = ss.accept();//阻塞式:没客户端连过来就一直等
String ip = s.getInetAddress().getHostAddress();
InputStream in = s.getInputStream();
byte[] buf = new byte[1024];
int len = in.read(buf);
String text = new String(buf,0,len);
System.out.println(ip+":"+text);
//以上是接收客户端发来的数据,对应图解in进来
//使用Socket的输出流,给客户端反馈数据,对应图解out出去
OutputStream out = s.getOutputStream();
out.write("收到......".getBytes());
s.close();
ss.close();
}
}