您的位置:首页 > 理论基础 > 计算机网络

Java TCP客户端服务器端交互

2016-07-24 08:51 483 查看
package com.knightsight.chatroom;
import java.net.*;
import java.io.*;
/*
* 输入流与输出流独立,客户端程序
*/
public class Client {
public static void main(String[] args) throws IOException,UnknownHostException{
Socket client =new Socket("localhost",9900);
//控制台输入流
BufferedReader console=new BufferedReader(new InputStreamReader(System.in));
DataOutputStream dos=new DataOutputStream(client.getOutputStream());
DataInputStream dis=new DataInputStream(client.getInputStream());
while(true){
String info=console.readLine();
//输出流
dos.writeUTF(info);
dos.flush();
//输入流
String str=dis.readUTF();
System.out.println(str);
}
}
}


package com.knightsight.chatroom;
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws IOException{
ServerSocket server=new ServerSocket(9900);
Socket socket=server.accept();

DataInputStream dis=new DataInputStream(socket.getInputStream());
String str=dis.readUTF();

DataOutputStream dos=new DataOutputStream(socket.getOutputStream());
dos.writeUTF("服务器已收到"+str);
dos.flush();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: