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

JAVA中Socket编程(一)---通过TCP协议实现通信

2015-12-04 22:59 676 查看
1.服务器端的实现:

public class Server {
public static void main(String[] args){
try {
//1.创建一个ServerSocket对象,并绑定端口
ServerSocket  server = new ServerSocket(8088);
Socket socket = null;
//2.创建 一个socket对象,监听套接字接口
int cnt=0;
System.out.println("*****服务器启动,等待客户端连接******");
while(true){
socket = server.accept();
//创建一个线程
ServerThread serverThread=new ServerThread(socket);
serverThread.start();

cnt++;
System.out.println("客户端的数量:"+cnt);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}


2.服务器多线程处理:

public class ServerThread extends Thread {
Socket socket = null;
public ServerThread(Socket socket){
this.socket=socket;
}
public void run(){
//3.获取输入流
InputStream is=null;
InputStreamReader isr=null;
BufferedReader br=null;
//5.对客户端进行响应
OutputStream os=null;
PrintWriter pw=null;
try {
is = socket.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
//4.读取客户端发过来的请求
String s = null;
while((s=br.readLine())!=null){
System.out.println("收到客户端请求:"+s);
}
socket.shutdownInput();
os = socket.getOutputStream();
pw = new PrintWriter(os);
pw.write("登陆成功,欢迎您!!!");
pw.flush();
socket.shutdownOutput();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(pw!=null)
pw.close();
if(os!=null)
os.close();
if(br!=null)
br.close();
if(isr!=null)
isr.close();
if(is!=null)
is.close();
if(socket!=null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


3.客户端的实现:

public class Client {
public static void main(String[] args){
try {
//1.创建一个Socket对象,并绑定Ip地址和端口
Socket socket = new Socket("127.0.0.1", 8088);
//2.获取Socket输出流,并包装为PW流
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
//3.向服务器发送请求
pw.write("usr: 叶良辰; password: 456");
pw.flush();
socket.shutdownOutput();
//4.接收服务器端的响应
InputStream is = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String s = null;
while((s=br.readLine())!=null){
System.out.println("收到客户端响应:"+s);
}
socket.shutdownInput();
//4.关闭相关资源
br.close();
is.close();
pw.close();
os.close();
socket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java socket tcp