[java]代码库
package com.gufengxiachen.sthreadchatapp;
/**
* @author GUXIA
*/
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ChatServer {
public static void main(String[] args) {
try {
//创建服务器端套接字,接受来自客户端的连接请求
ServerSocket ss=new ServerSocket(9999);
Socket s=ss.accept();
//获取客户端套接字的输出流
OutputStream os=s.getOutputStream();
DataOutputStream dos=new DataOutputStream(os);
//获取客户端输入流
InputStream is=s.getInputStream();
DataInputStream dis=new DataInputStream(is);
//创建字符输入流接受键盘输入
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
String message;
while(true){
//获取客户端输入流,并打印在屏幕上,如果客户端说的是“再见”,退出
message=dis.readUTF();
System.out.println("客户端:"+message);
if(message.equals("再见"))
break;
//读取键盘输入并写入到输出流(客户端的输入流)
message=br.readLine();
dos.writeUTF(message);
}
dis.close();
dos.close();
ss.close();
s.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
//源代码片段来自云代码http://yuncode.net
package com.gufengxiachen.sthreadchatapp;
/**
* @author GUXIA
*/
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
public class ChatClient {
public static void main(String[] args) {
try {
//创建客户端套接字
Socket sc=new Socket("localhost",9999);
//获取套接字输入流
InputStream is=sc.getInputStream();
DataInputStream dis=new DataInputStream(is);
//获取套接字输出流
OutputStream os=sc.getOutputStream();
DataOutputStream dos=new DataOutputStream(os);
//创建字符输入流接受键盘输入
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
//聊天
String message;
while(true){
//读取键盘输入的字符,写到客户端输出流
message=br.readLine();
dos.writeUTF(message);
if(message.equals("再见"))
break;
//读取服务器端的数据并打印到屏幕上
message=dis.readUTF();
System.out.println("服务器:"+message);
}
dis.close();
dos.close();
sc.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
//源代码片段来自云代码http://yuncode.net