socketserver.java
来自「有关java的源程序,为讲授java程序设计课程使用」· Java 代码 · 共 106 行
JAVA
106 行
import java.net.*;
import java.io.*;
public class SocketServer
{ public static void main(String args[])
{ ServerSocket ss1=null;
ServerSocket ss2=null;
int port1 = 1000; // for client one
int port2 = 1001; // for client two
boolean listening=true;
try
{ ss1 = new ServerSocket(port1);
ss2 = new ServerSocket(port2);
}
catch(IOException e)
{ System.err.println("Cannot Listen.");
System.exit(-1);
}
port1=ss1.getLocalPort();
System.out.println("Listening on Port:"+port1);
System.out.println("Listening on Port:"+port2);
while(listening)
{ Socket cs1 = null;
Socket cs2 = null;
try
{ cs1 = ss1.accept();
}
catch(IOException e)
{ System.err.println("Accept failed:"+ss1.getLocalPort());
System.err.println("Accept failed:"+ss2.getLocalPort());
continue;
}
try
{ cs2 = ss2.accept();
}
catch(IOException e)
{ System.err.println("Accept failed:"+ss1.getLocalPort());
System.err.println("Accept failed:"+ss2.getLocalPort());
continue;
}
new SocketServerThread(cs1, cs2).start();
//new SocketServerThread(cs2, cs1).start();
}
try
{ ss1.close();
ss2.close();
}
catch(IOException e)
{ System.err.println("Canot closed server socket.");
}
}
}
class SocketServerThread extends Thread
{ Socket s1 = null;
Socket s2 = null;
SocketServerThread(Socket socket1, Socket socket2)
{ super("SocketServerThread");
s1 = socket1;
s2 = socket2;
}
public void run()
{ try
{
DataInputStream sin1=new DataInputStream(s1.getInputStream());
PrintStream sout1=new PrintStream(s1.getOutputStream());
DataInputStream sin2=new DataInputStream(s2.getInputStream());
PrintStream sout2=new PrintStream(s2.getOutputStream());
String acceptText1="",acceptText2="";
boolean ClientOne=false,ClientTwo=false;
while(true)
{
if((acceptText1=sin1.readLine())!=null)
{
ClientOne=true;
sout2.println("Client One:"+acceptText1);
System.out.println("srv_Client2 One:"+acceptText1);
System.out.println("srv_Client1 Name:"+s1.getLocalAddress());
}
if((acceptText2=sin2.readLine())!=null)
{
ClientTwo=true;
sout1.println("Client Two:"+acceptText2);
System.out.println("srv_Client Two:"+acceptText2);
}
if((ClientOne=false)&&(ClientTwo=false))
break;
}
sout1.close();
sin1.close();
sout2.close();
sin2.close();
s1.close();
s2.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?