import java.io.IOException;
import java.net.*;
public class TCP_Server {
public static void main(String[] args) {
new ConnectionThread().start();
}
}
class ConnectionThread extends Thread {
@Override
public void run() {
try {
ServerSocket ss = new ServerSocket(8989);
while(true){
Socket s = ss.accept();
System.out.println("接收到一个用户的连接" + s.getInetAddress());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
目前,这个服务器端没有处理客户端发送的数据的功能,我们需要利用多线程接收处理客户端的数据。
构建一个线程类,构造方法中把Socket对象传递过来。
import java.io.IOException;
import java.io.InputStream;
import java.net.*;
public class TCP_Server {
public static void main(String[] args) {
new ConnectionThread().start();
}
}
class ConnectionThread extends Thread {
@Override
public void run() {
try {
ServerSocket ss = new ServerSocket(8989);
while(true){
Socket s = ss.accept();
System.out.println("接收到一个用户的连接" + s.getInetAddress());
new ServerThread(s).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerThread extends Thread {
public ServerThread(Socket s){
this.s=s;
}
private Socket s =null;
@Override
public void run() {
try {
InputStream ips = s.getInputStream();
byte[] buf = new byte[1024];
int length = -1;
System.out.println("-------------------------------");
System.out.println("来自"+s.getInetAddress()+"客户端的连接");
while((length = ips.read(buf))>-1)
System.out.println(new String(buf,0,length));
} catch (Exception e) {
e.printStackTrace();
}
}
}