黑马程序员技术交流社区
标题:
一个java小程序
[打印本页]
作者:
请许我一世安宁
时间:
2015-10-26 21:18
标题:
一个java小程序
/*
这是一个能实现两个人聊天的小程序
*/
import java.net.*;
import java.io.*;
class Chat{
public static void main(String[] args)throws Exception{
ServerSocket ss = new ServerSocket(10002);
new Thread(new ServerThread(ss)).start();
try{
Thread.sleep(5000);
Socket s = new Socket("192.168.1.71",10001);
Thread t = new Thread(new ClientThread(s));
t.start();
}
catch (Exception e){
throw new RuntimeException("线程出现异常");
}
}
}
class ClientThread implements Runnable{
private Socket s;
public ClientThread(Socket s){
this.s = s;
}
public void run(){
BufferedReader bufr = null;
BufferedWriter bufOut = null;
try{
bufr = new BufferedReader(new InputStreamReader(System.in));
bufOut = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String line = null;
while((line=bufr.readLine())!=null){
if (line.equals("exit")) {
System.out.print("发送完毕");
bufOut.write(line);
bufOut.flush();
s.shutdownOutput();
break;
}
bufOut.write(line);
bufOut.newLine();
bufOut.flush();
}
bufOut.close();
s.close();
}
catch (Exception e){
throw new RuntimeException("发送消息失败");
}
}
}
class ServerThread implements Runnable{
private ServerSocket ss;
BufferedWriter bufOut = null;
public ServerThread(ServerSocket ss){
this.ss = ss;
}
public void run(){
Socket s;
try{
s = ss.accept();
}
catch (Exception ee){
throw new RuntimeException("服务端建立失败");
}
String ip = s.getInetAddress().getHostAddress();
try{
System.out.println(ip+".....connected");
BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
//PrintWriter ps = new PrintWriter(s.getOutputStream(),true);
String str = null;
while((str=bufIn.readLine())!=null){
if("exit".equals(str)){
System.out.println(s.getInetAddress().getHostName()+"发送的消息"+str);
break;
}
System.out.println(s.getInetAddress().getHostAddress()+"发送的消息"+str);
}
s.shutdownInput();
bufOut = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
bufOut.write("服务器已接收到消息");
bufOut.flush();
s.shutdownOutput();
s.close();
}
catch(Exception e){
throw new RuntimeException("接收消息失败");
}
finally{
if(bufOut!=null){
try {
bufOut.close();
}
catch (Exception e){
e.printStackTrace();
}
}
if(s!=null){
try{
s.close();
}
catch (Exception e){
e.printStackTrace();
}
}
if(ss!=null){
try{
ss.close();
}
catch (Exception e){
e.printStackTrace();
}
}
}
}
}
复制代码
作者:
ppaapc
时间:
2015-10-26 21:57
有点意思
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2