启动项目后,输入服务器端口号,多开可连接目标服务器,进行TCP/IP的收发操作。快来试试吧!
Client and server integrated code
package SocketDemo6;
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class CS6 {
private static Socket socket;
private static ServerSocket serverSocket;
public boolean BuildClient(String IP, int port){
try {
System.out.println("Starting client~~");
socket = new Socket(IP,port);
System.out.println("Client Started");
return true;
} catch (Exception e) {
System.out.println("Port number invalid!");
return false;
}
}
public void BuildServer(int port){
try {
System.out.println("Starting server~~");
serverSocket = new ServerSocket(port);
System.out.println("Server started");
} catch (IOException e) {
e.printStackTrace();
}
}
public void ClientComm(){
try {
OutputStream os = socket.getOutputStream();
PrintWriter pw = new PrintWriter(os,true);
Scanner sc = new Scanner(System.in);
while (true){
String s = sc.nextLine();
pw.println(s);
if ("exit".equalsIgnoreCase(s)){
System.out.println("Client shutting down!");
pw.close();
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void ServerComm(){
while (true){
try {
Socket sa = serverSocket.accept();
System.out.println(sa.getRemoteSocketAddress() + " client connected!");
new Thread(new Runnable() {
@Override
public void run() {
try {
InputStream is = sa.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String s;
while ((s = br.readLine()) != null){
if ("exit".equalsIgnoreCase(s)){
System.out.println(sa.getRemoteSocketAddress() + " client disconnected!");
break;
}else{
System.out.println(sa.getRemoteSocketAddress() + " client send message: " + s);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
//Server
System.out.println("Please enter your server port number:");
Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt();
CS6 server = new CS6();
server.BuildServer(i);
new Thread(new Runnable() {
@Override
public void run() {
server.ServerComm();
}
}).start();
//Client
while (true) {
System.out.println("Please enter a port number you want to send message:");
int j = scanner.nextInt();
CS6 client = new CS6();
if (client.BuildClient("localhost",j)){
client.ClientComm();
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}