public class SocketThread implements Runnable{
Socket s=null;
@Override
public void run() {
Scanner input =new Scanner(System.in);
BufferedReader br=null;
BufferedWriter bw=null;
try {
if (s!=null){
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//1.接受用户发送的请求信息
String request=br.readLine();
System.out.println(s.getInetAddress().getHostAddress()+"说:"+request);
//2.写出给用户的响应信息
System.out.println("请输入要给用户的响应信息");
String response=input.next();
bw.write(response);
bw.newLine();
bw.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bw.close();
br.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class TcpServer {
public static void main(String[] args) {
ServerSocket ss=null;
Socket s=null;
try {
ss=new ServerSocket(8090);
while (true){
System.out.println("等待接受用户的请求");
s=ss.accept();
SocketThread st=new SocketThread();
st.s=s;
Thread t=new Thread(st);
t.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class TcpClient1 {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
Socket s=null;
BufferedWriter bw=null;
BufferedReader br=null;
try {
//1.创建客户端
s=new Socket("192.168.1.102", 8090);
//2.获取输入输出流
bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
//3.使用输出流给服务器请求
System.out.println("输入要对服务器说的话");
String reques=input.next();
//写出请求
bw.write(reques);
//输出换行符,代表信息已经结束
bw.newLine();
bw.flush();
//4.使用输入流获取服务器给的响应
String response=br.readLine();
System.out.println("服务器的响应是:"+response);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
br.close();
bw.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class TcpClient2 {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
Socket s=null;
BufferedWriter bw=null;
BufferedReader br=null;
try {
//1.创建客户端
s=new Socket("192.168.1.102", 8090);
//2.获取输入输出流
bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
br=new BufferedReader(new InputStreamReader(s.getInputStream()));
//3.使用输出流给服务器请求
System.out.println("输入要对服务器说的话");
String reques=input.next();
//写出请求
bw.write(reques);
//输出换行符,代表信息已经结束
bw.newLine();
bw.flush();
//4.使用输入流获取服务器给的响应
String response=br.readLine();
System.out.println("服务器的响应是:"+response);
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
br.close();
bw.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
|