socket一个服务端多个客户端,多线程这么实现
packagecn.u6;importjava.io.*;importjava.net.*;publicclassSocketClient{publicstaticvoi...
package cn.u6;
import java.io.*;
import java.net.*;
public class SocketClient {
public static void main(String argv[]){
if(argv.length != 2) {
System.out.println("Parameter:");
return;
}
String strIP = argv[0];
int iPort = Integer.valueOf(argv[1]);
try {
//与服务器建立连接
Socket socket = new Socket(strIP, iPort);
//获得socket的输入流和输出流
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//先接收数据
String line = in.readLine();
System.out.println("服务器说:" + line);
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
while(!line.equals("bye")) {
//从控制台接收用户输入并发送至服务器
System.out.print("客户端说:");
String strMsg = reader.readLine();
out.println(strMsg);
//从服务器接收响应数据
line = in.readLine();
System.out.println("服务器说:" + line);
}
//关闭流并断开连接
out.close();
in.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} 展开
import java.io.*;
import java.net.*;
public class SocketClient {
public static void main(String argv[]){
if(argv.length != 2) {
System.out.println("Parameter:");
return;
}
String strIP = argv[0];
int iPort = Integer.valueOf(argv[1]);
try {
//与服务器建立连接
Socket socket = new Socket(strIP, iPort);
//获得socket的输入流和输出流
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//先接收数据
String line = in.readLine();
System.out.println("服务器说:" + line);
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
while(!line.equals("bye")) {
//从控制台接收用户输入并发送至服务器
System.out.print("客户端说:");
String strMsg = reader.readLine();
out.println(strMsg);
//从服务器接收响应数据
line = in.readLine();
System.out.println("服务器说:" + line);
}
//关闭流并断开连接
out.close();
in.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询