黑马程序员技术交流社区
标题:
Tcp Demo
[打印本页]
作者:
fmi110
时间:
2015-10-7 13:11
标题:
Tcp Demo
a
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
public class TcpDemo2 {
/**
* tcp聊天程序
* @throws IOException
* @throws UnknownHostException
*/
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("192.168.220.1",10006);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
System.out.println("客户端启动...");
while((line = br.readLine())!=null){
bw.write(line);
bw.newLine();
bw.flush();
System.out.println(s.getInputStream().read()+" 来自:"+s.getInetAddress().getHostName());
}
}
}
class Server{
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(10006);
Socket s = ss.accept();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = null;
System.out.println("服务器启动...");
while((line = br.readLine())!=null){
System.out.println("等待信息...");
System.out.println(s.getInetAddress().getHostAddress()+" 发来信息:"+line);
bw.write("Roger!!");
bw.newLine();
bw.flush();
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2