服务器端:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Server server = new Server(8080);
}
}
class Server{
private int port;
public Server(int port){
this.port=port;
start();
}
public void start(){
try {
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("服务器已启动,监听端口为:"+port);
System.out.println("正在等待客户端");
Socket socketAccept = serverSocket.accept();
BufferedReader in =new BufferedReader(new InputStreamReader(socketAccept.getInputStream()));
PrintWriter out =new PrintWriter(socketAccept.getOutputStream(),true);
out.println("服务器端连接成功");
out.println("输入quit断开服务器的连接");
boolean done = false;
while(!done){
String line = in.readLine();
if(line == null){
done=true;
}else{
System.out.println("来自客户端的信息"+line);
out.println("来自服务器端的信息:"+line);
if(line.trim().equals("quit"))
done= true;
}
}
socketAccept.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客户端:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPClient {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Client c = new Client ("127.0.0.1",8080);
try {
c.connect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Client{
String ip;
int port;
Socket Server = null;
Boolean isConnected;
public Client(String ip,int port){
this.ip=ip;
this.port=port;
}
public void connect() throws IOException{
Socket server = new Socket(ip,port);
BufferedReader in =new BufferedReader(new InputStreamReader( server.getInputStream()));
PrintWriter out = new PrintWriter(server.getOutputStream());
BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));
if(server.isConnected()){
isConnected = true;
System.out.println("服务器信息:"+in.readLine());
}
while(isConnected){
System.out.println("服务器信息:"+in.readLine());
System.out.println("请输入>");
String str=wt.readLine();
if(str.equals("quit")){
isConnected = false;
}
out.println(str);
out.flush();
}
out.close();
in.close();
wt.close();
server.close();
}
}
具体怎么操作啊
不懂编码问题,在哪里改啊
楼主可以试下,如果不行,把代码中的GBK换成UTF-8再试下。
怎么看啊
追答整两个输出语句看下不就得了