版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37527943/article/details/84666963
导读
1.计算机网络简介
2.基于TCP协议的Socket编程
计算机网络简介
基于TCP协议的Socket编程
HandleThread.java
package com.hala.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class HandleThread extends Thread {
private Socket socket;
BufferedReader brSocket;
public HandleThread (Socket socket){
this.socket=socket;
try {
//获取输入流
//这里之所以放在构造方法里,就是要保证socket已经被赋值
brSocket=new BufferedReader(
new InputStreamReader(socket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 负责处理服务器和每一个客户机的交互
* 一个客户机一个线程
*/
@Override
public void run() {
try {
String line=brSocket.readLine();
System.out.println("收到:"+line);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
//关闭资源
try {
brSocket.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
TCPServer.java
package com.hala.net;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//1.创建ServerSocket,传入一个端口号
ServerSocket serverSocket=new ServerSocket(6666);
while(true){
//2.接收用户的请求
//连接成功返回socket与客户端交互,否则阻塞
Socket socket=serverSocket.accept();
//交互
//getInetAddress()返回此连接的远程IP地址 是 InetAddress对象
//getHostAddress()是将结果作为字符串返回
System.out.println(socket.getInetAddress().getHostAddress()
+"连接成功");
//开辟一个新的线程,负责交互
HandleThread thread=new HandleThread(socket);
thread.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
TCPClient.java
package com.hala.net;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class TCPClient {
public static void main(String[] args) {
// TODO Auto-generated method stub
Socket socket=null;
PrintWriter pw=null;
Scanner input=new Scanner(System.in);
try {
//与服务器建立连接,指定IP和端口号
socket=new Socket("172.31.0.1",6666);
//为socket建立一个输出通道,true的作用是刷新缓存
pw=new PrintWriter(socket.getOutputStream(),true);
while(true){
System.out.println("请输入:");
String line=input.next();
pw.println(line);
//可以多次发送的技巧
if(line.equals("exit")){
break;
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(pw!=null){
pw.close();
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}