java的聊天室项目代码 java的聊天室项目代码是什么( 四 )


}
private class IncomingMessageHandler implements Runnable {
@Override
public void run() {
try {
while (true) {
String message = reader.readLine();
if (message == null) {
break;
}
System.out.println(message);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
close();
}
}
}
private class OutgoingMessageHandler implements Runnable {
@Override
public void run() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
while (true) {
String message = reader.readLine();
if (message.equals("quit")) {
break;
}
writer.println(name + ": " + message);
}
} catch (IOException e) {
e.printStackTrace;
} finally {
close();
}
}
}
求Java Socket 聊天室代码两个类,实现交互
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class MutiChat
{
public static void main(String[] args)
{
MutiChat mc = new MutiChat();
mc.receive().start();
mc.send().start();
}
/**
* 接收信息
*
* @return
*/
private Thread receive()
{
return new Thread()
{
public void run()
{
ServerSocket server_socket = null;
Socket sk = null;
BufferedReader in = null;
try
{
server_socket = new ServerSocket(7777);
sk = server_socket.accept();
in = new BufferedReader(new InputStreamReader(sk
.getInputStream()));
while (true)
{
String str = in.readLine();
System.out.println(str);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
};
}
private Thread send()
{
return new Thread()
{
public void run()
{
Socket client_socket = null;
BufferedReader in = null;
PrintWriter out = null;
while (true)
{
try
{
client_socket = new Socket("127.0.0.1", 8888);
in = new BufferedReader(
new InputStreamReader(System.in));
out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(client_socket
.getOutputStream())), true);
while (true)
{
String str = in.readLine();
out.println(str);
}
} catch (Exception e)
{
try
{
Thread.sleep(1000);
} catch (Exception ex)
{
ex.printStackTrace();
}
}
}
}
};
}
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class MutiChat2
{
public static void main(String[] args)
{
MutiChat2 mc = new MutiChat2();
mc.receive().start();
mc.send().start();
}
/**
* 接收信息
*
* @return
*/
private Thread receive()
{
return new Thread()
{
public void run()
{
ServerSocket server_socket = null;
Socket sk = null;
BufferedReader in = null;
try
{
server_socket = new ServerSocket(8888);
sk = server_socket.accept();
in = new BufferedReader(new InputStreamReader(sk
.getInputStream()));
while (true)
{
String str = in.readLine();
System.out.println(str);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
};
}
private Thread send()

推荐阅读