代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
* 发送消息线程
*/
class Send extends Thread{
private Socket socket;
public Send(Socket socket){
this.socket =socket;
}
@Override
public void run() {
this.sendMsy();
}
/**
* 发送消息
*/
private void sendMsy(){
Scanner scanner =null;
PrintWriter pw =null;
try{
scanner =new Scanner(System.in);
pw =new PrintWriter(this.socket.getOutputStream());
while(true){
String str =scanner.nextLine();
pw.println(str);
pw.flush();
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (scanner!=null){
scanner.close();
}
if (pw!=null){
pw.close();
}
if (socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
/**
* 接收消息的线程
*/
class receive extends Thread{
private Socket socket=null;
public receive(Socket socket){
this.socket =socket;
}
@Override
public void run() {
this.receiveMsg();
}
/**
* 用于接收对方消息
*/
private void receiveMsg(){
BufferedReader br =null;
try{
br =new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
while(true){
String mr = br.readLine();
System.out.println("B说:"+mr);
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public class ChatSocketServer {
public static void main(String[] args) {
ServerSocket serverSocket =null;
try{
serverSocket =new ServerSocket(8888);
System.out.println("服务端已启动等待连接");
Socket socket = serverSocket.accept();
System.out.println("连接成功!");
new Send(socket).start();
new receive(socket).start();
}catch(Exception e){
e.printStackTrace();
}finally {
if (serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
结果: