[Socket]Socket聊天小程序

时间:2022-06-20 08:57:54

一个简单是Socket聊天小程序,读写操作在不同的线程中。服务器端采用线程池。

1、Server

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class Server
{
private static final ExecutorService threadWorkers = Executors
.newCachedThreadPool(); private void start() throws IOException
{
ServerSocket server = new ServerSocket(8899);
while (true)
{
Socket socket = server.accept();
threadWorkers.execute(new ThreadWorker(socket));
} } public static void main(String[] args) throws IOException
{
Server server = new Server();
server.start();
}
}

2、Client

import java.net.Socket;

public class Client
{
public static void main(String[] args) throws Exception
{
Socket socket = new Socket("127.0.0.1", 8899);
new Thread(new InputReceiverAndSender(System.in,socket.getOutputStream())).start();
new Thread(new SocketReader("Server", socket.getInputStream())).start();
}
}

3、InputReceiverAndSender

import java.io.*;

public class InputReceiverAndSender implements Runnable
{
private BufferedReader receiver; private BufferedWriter sender; private InputStream input; static int i = 0; String name; public InputReceiverAndSender(InputStream input, OutputStream output)
{
super();
name = ""+(i++);
this.input = input;
this.receiver = new BufferedReader(new InputStreamReader(input));
this.sender = new BufferedWriter(new OutputStreamWriter(output));
} public void run()
{
String message = null;
try
{
try
{
do
{
synchronized (input)
{
message = receiver.readLine();
}
System.out.println(name+":"+message);
sender.write(message);
// 写入行结束标志,如果省略这句,另一端是无法读入的
sender.newLine();
sender.flush();
}
while (message != null);
}
finally
{
receiver.close();
sender.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

4、SocketReader

import java.io.*;

public class SocketReader implements Runnable
{
private BufferedReader receiver;
private String name; public SocketReader(String name, InputStream input)
{
super();
this.name = name;
this.receiver = new BufferedReader(new InputStreamReader(input));
} public void run()
{
try
{
try
{
String message = null;
while ((message = receiver.readLine()) != null)
{
System.out.println(name + ":" + message);
}
}
finally
{
receiver.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

5、ThreadWorker

import java.io.IOException;
import java.net.Socket; public class ThreadWorker implements Runnable
{ private static int id = 1; private Socket socket; public ThreadWorker(Socket socket)
{
this.socket = socket;
} @Override
public void run()
{
System.out.println("connected...");
// 输入及发送线程
try
{
new Thread(new InputReceiverAndSender(System.in,
socket.getOutputStream())).start();
// 读线程
new Thread(new SocketReader("Agent" + (id++),
socket.getInputStream())).start();
}
catch (IOException e)
{
e.printStackTrace();
} }
}