TCP多线程Java具体代码实现
客户端
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws Exception {
String userInput = null;
String echoMessage = null;
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
Socket socket = new Socket("127.0.0.1", 8189);
System.out.println("Connected to Server");
InputStream inStream = socket.getInputStream();
OutputStream outStream = socket.getOutputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inStream));
PrintWriter out = new PrintWriter(outStream);
while ((userInput = stdIn.readLine()) != null){
out.println(userInput);
out.flush();
echoMessage =in.readLine();
System.out.println("Echo from server: " + echoMessage);
}
socket.close();
}
}
服务端
import java.io.*;
import java.net.*;
public class MultiThreadEchoServer {
public static void main(String[] args) throws Exception{
ServerSocket listenSocket = new ServerSocket(8189);
Socket socket = null;
int count = 0;
System.out.println("Server listening at 8189");
while (true){
socket = listenSocket.accept();
count ++;
System.out.println("The total number of clients is " + count);
ServerThread serverThread = new ServerThread(socket, count);
serverThread.run();
}
}
}
服务端线程段
import java.io.*;
import java.net.*;
public class ServerThread {
Socket socket = null;
int count;
public ServerThread(Socket socket, int count){
this.socket = socket;
this.count = count;
}
public void run(){
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
OutputStream os = null;
PrintWriter pw = null;
try{
is = socket.getInputStream();
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
os = socket.getOutputStream();
pw = new PrintWriter(os);
String info = null;
while ((info = br.readLine()) != null){
System.out.println("Message from client" + count + ":" + info);
pw.println(info);
pw.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (pw != null)
pw.close();
if (os != null)
os.close();
if (br != null)
br.close();
if (isr != null)
isr.close();
if (is != null)
is.close();
if (socket != null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}