没什么好说的,直接上代码:
首先是服务器,多线程服务器我们可以通过两种方法实现,一种继承Thread,一种实现Runnable接口,以继承为例:
java代码:TCP_server.java
package com.wpf.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class TCP_server extends Thread{
private Socket socket;
public TCP_server(Socket socket){
this.socket = socket;
}
@Override
public void run() {
try {
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
BufferedReader buffered = new BufferedReader(new InputStreamReader(in));
PrintWriter writer = new PrintWriter(out);
System.out.println(buffered.readLine());
writer.println("我是服务器,收到");
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void openServer() throws Exception{
ServerSocket server = new ServerSocket(9000);
while(true){
new TCP_server(server.accept()).start();
}
}
}
代码应注意1.文件流的包装
2.write.println(".......");千万不能写成write.write(".........");
3. ServerSocket server = new ServerSocket(9000);
while(true){
new TCP_server(server.accept()).start();
}的server在循环外面,必须启动该线程,及调用start();
接着,客户端代码:TCP_client
package com.wpf.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class TCP_client {
public static void main(String[] args) throws Exception{
Socket socket = new Socket("192.168.1.106", 9000);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
BufferedReader buffered = new BufferedReader(new InputStreamReader(in));
PrintWriter writer = new PrintWriter(out);
writer.println("client");
writer.flush();
System.out.println(buffered.readLine());
}
}
启动服务:
StartServer.java
package com.wpf.test;
public class StartServer {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
TCP_server.openServer();
} catch (Exception e) {
e.printStackTrace();
}
}
}