1.ServerSocket 用一个端口并发(多线程)接收多个Socket。
注意:accept()语句在run() 语句块外面
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Serv {
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket ss=new ServerSocket(6000);
while(true){
Socket sc=ss.accept(); //同时(并发)接收发送给服务器6000端口的多个客户端
//accept()在run() 语句块外面
Test t=new Test(sc);
t.start();
}
}
}
class Test extends Thread {
Socket sc;
Test(Socket sc){
this.sc=sc;
}
public void run() {
while (true) {
try {
while (true) {
OutputStream os = sc.getOutputStream();
os.write('f');
InputStream is = sc.getInputStream();
System.out.println((char) is.read());
Thread.sleep(1000);
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
2.如accept()语句在run() 语句块里面.
一个端口只能接收一个Socket.(单线程)如果只是处理一个端口而且不需要接入多个客户端,完全可以循环不用线程的方式。
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Serv {
public static void main(String[] args) throws IOException, InterruptedException {
ServerSocket ss=new ServerSocket(6000);
Test t=new Test(ss);
t.start();
}
}
class Test extends Thread {
ServerSocket ss;
Test(ServerSocket ss){
this.ss=ss;
}
public void run() {
while(true) {
Socket sc = null;
try {
sc = ss.accept();
} catch (IOException e) {
throw new RuntimeException(e);
}
while (true) {
try {
while (true) {
OutputStream os = sc.getOutputStream();
os.write('f');
InputStream is = sc.getInputStream();
System.out.println((char) is.read());
Thread.sleep(1000);
}
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
}
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Kf2 {
public static void main(String[] args) throws IOException, InterruptedException {
Socket sc=new Socket("114.132.48.228",6000);
while(true){
OutputStream os=sc.getOutputStream();
os.write('2');
Thread.sleep(1000);
InputStream is=sc.getInputStream();
System.out.println((char)is.read());
}
}
}