socket聊天 java_Java使用socket实现两人聊天对话

import java.io.*;importjava.net.ServerSocket;importjava.net.Socket;importjava.util.Scanner;/*** User: HYY

* Date: 13-10-29

* Time: 下午9:57

* To change this template use File | Settings | File Templates.*/

public classServer {public static final int SERVER_PORK = 10000;public static void main(String[] args) throwsIOException, InterruptedException {

ServerSocket serverSocket= newServerSocket(SERVER_PORK);

System.out.println("正在监听 " + SERVER_PORK + " 端口!");

Socket socket;

BufferedReader bufferedReader;while (true) {

socket=serverSocket.accept();

System.out.println("一客户端连接。");

Thread writerThread= new Thread(newMyServerWriter(socket));

writerThread.start();

bufferedReader= new BufferedReader(newInputStreamReader(socket.getInputStream()));try{

String msg;//客户端发过来的信息

while ((msg = bufferedReader.readLine()) != null) {

System.out.println("##客户端:" +msg);

}

}catch(IOException e) {try{if (!socket.isClosed()) {

socket.close();

}

}catch(IOException e1) {

System.out.println("关闭socket出现错误");

}

}

System.out.println("提示:当前客户端已经断开连接,服务器正等待下一个客户端的连接。");

}

}

}class MyServerWriter implementsRunnable {private Socket socket = null;privatePrintWriter printWriter;privateScanner scanner;public MyServerWriter(Socket socket) throwsIOException {this.socket =socket;

scanner= newScanner(System.in);

printWriter= new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);

}

@Overridepublic voidrun() {

String msg;//要发送的信息

try{while ((msg = scanner.nextLine()) != null) {if (msg.equals("88")) {if (!socket.isClosed()) {

System.out.println("服务器手动与客户端断开");

socket.close();

}break;

}

printWriter.println(msg);

}

}catch(IOException io) {

System.out.println("关闭socket出现问题");

}catch(Exception e) {

System.out.println("异常关闭客户端(可能是直接关闭退出窗口)");

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值