好久没写socket代码了,也忘了八九成了……话不多说!直接上代码吧!
Server服务
package test1;
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args) throws IOException{
ServerSocket server = new ServerSocket(9999);
System.err.println("服务码-SP:" + server.getLocalSocketAddress());
System.err.println("启动服务成功,端口: " + server.getLocalPort());
System.err.println("监听器启动成功……");
Socket client = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream());
while(true){
String str;
str = in.readLine();
System.out.println(str);
out.println("你好: " + str);
out.flush();
if(str.equals("end"))
break;
}
client.close();
}
}
Client客户端
package test1;
import java.net.*;
import java.io.*;
public class Client{
static Socket server;
public static void main(String[] args)throws Exception{
server = new Socket(InetAddress.getLocalHost(),9999); //xxx.xxx.x.xxxIP地址
System.err.print("请输入:");
BufferedReader in=new BufferedReader(new InputStreamReader(server.getInputStream()));
PrintWriter out=new PrintWriter(server.getOutputStream());
BufferedReader wt=new BufferedReader(new InputStreamReader(System.in));
while(true){
String str=wt.readLine();
out.println(str);
out.flush();
if(str.equals("end")){
break;
}
System.out.println(in.readLine());
}
server.close();
}
}