客户端
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.UnknownHostException;
public class ClientText {
public static final String ip="127.0.32.42";
public static int port=7890;
private Socket client_s;
public ClientText(){
try{
client_s=new Socket(ip,port);
}catch(UnknownHostException e){
e.printStackTrace();
}catch(IOException c){
c.printStackTrace();
}
}
public void setConnection() throws IOException{
InputStream is;
OutputStream os;
try{
is=client_s.getInputStream();
os=client_s.getOutputStream();
BufferedReader sys_br=new BufferedReader(new InputStreamReader(System.in));
BufferedReader client_br=new BufferedReader(new InputStreamReader(is));
PrintWriter client_pw=new PrintWriter(os,true);
String warnStr=null;
if((warnStr=client_br.readLine())!=null){
System.out.println(warnStr);
}
while((warnStr=sys_br.readLine())!=null){
client_pw.println(warnStr);
break;
}
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String[] args) {
ClientText myclient=new ClientText();
try {
myclient.setConnection();
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务端
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.BufferedReader;
public class ServerText{
private ServerSocket ss;
public static final int port=7890;
public ServerText(){
try{
ss=new ServerSocket(port);
}catch(IOException e){
e.printStackTrace();
}
}
public void setConnection()throws IOException{
Socket server_s;
OutputStream os;
InputStream is;
try{
server_s=ss.accept();
os=server_s.getOutputStream();
is=server_s.getInputStream();
PrintWriter server_pw=new PrintWriter(os,true);
BufferedReader server_br=new BufferedReader(new InputStreamReader(is));
String msg=null;
server_pw.println("连接成功,请输入一些数据传递到服务端");
if((msg=server_br.readLine())!=null){
System.out.println("客户端传递过来的数据为:"+msg);
server_pw.println("数据传输成功");
}else{
server_pw.println("数据传输失败,出现错误");
}
}catch(IOException e){
e.printStackTrace();
}
}
public static void main(String args[]) throws IOException{
ServerText server_text=new ServerText();
server_text.setConnection();
}
}