tcp客户端和服务端互发消息

先封装一个工具类

package com.wxh.tcp;
//点对点聊天

import java.io.*;
import java.net.*;

public class Connection extends Thread {
	private Socket socket;
	private PrintWriter pw;
	private BufferedReader br;	
	
	public Connection(Socket socket) {
		super();
		this.socket = socket;
		//直接开启线程
		this.start();
	}

	//发送信息的方法
	public void send(String msg){
		//使用socket将msg写出去
		try {
			if(pw==null){
				pw=new PrintWriter(socket.getOutputStream());
			}
			//输出信息
			pw.println(msg);
			pw.flush();			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//关闭socket
	public void disConnect(){
		if(socket!=null){
			try {
				socket.close();
			} catch (Exception e) {
			}
		}
	}
	
	
	//接收功能(线程)
	public void run() {
		//不断读取服务器数据
		try {
			if(br==null){
				br=new BufferedReader
						(new InputStreamReader(socket.getInputStream()));
			}
			String msg=null;
			while((msg=br.readLine())!=null){
				System.out.println(msg);
			}			
		} catch (SocketException e) {
			System.out.println("下线了");
		} catch (IOException e) {
			e.printStackTrace();
		}	
	}
	
	public String getIp(){
		return this.socket.getInetAddress().getHostAddress();
	}
	
}

服务端代码

package com.wxh.tcp;
//这是服务端
import java.io.*;
import java.net.*;

public class ChatServer {

	public static void main(String[] args) {
		Connection connection=null;
		try {
			ServerSocket serverSocket=new ServerSocket(9090);
			Socket socket=serverSocket.accept();
			
			System.out.println(socket.getInetAddress()+"上线了");
			
			connection =new Connection(socket);
	
			//监听控制台,发送消息,服务端也可以发送消息
			BufferedReader br=new BufferedReader(new InputStreamReader(System.in));			
			String sendMsg=null;
			while((sendMsg=br.readLine())!=null){
				connection.send(sendMsg);
			}			
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(connection!=null){
				connection.disConnect();
			}
		}
	}

}

客户端代码

package com.wxh.tcp;

import java.io.*;
import java.net.*;

public class ChatClient {
	public static void main(String[] args) {
		Connection  connection=null;
		try {
			Socket socket=new Socket("125.220.70.143",9090);
			System.out.println("已连接服务器");
			
			connection=new Connection(socket);
			
			//监听控制台,发送消息,客户端发送消息
			BufferedReader br=new BufferedReader
					(new InputStreamReader(System.in));
			
			String sendMsg=null;
			while((sendMsg=br.readLine())!=null){
				connection.send(sendMsg);
			}			
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
}



  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值