先封装一个工具类

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();
}
}
}