62,633
社区成员
发帖
与我相关
我的任务
分享
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerTest {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(8000);
Socket socket = ss.accept();
InputStream ins = socket.getInputStream();
OutputStream outs = socket.getOutputStream();
byte[] temp = new byte[512];
int size = 0;
while ((size = ins.read(temp)) != -1) {
String s = new String(temp, 0, size);
System.out.println("来自客户端的消息:" + s);
outs.write("返回给客户的信息".getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class ClientTest {
public static void main(String[] args) {
try {
Socket socket =new Socket("127.171.0.101",10000);
InputStream ins=socket.getInputStream();
OutputStream outs=socket.getOutputStream();
byte[] temp=new byte[512];
String s;
int size=0;
outs.write("test".getBytes());
size=ins.read(temp);
s=new String(temp,0,size);
if(s!=null){
System.out.println("A");
}else{
System.out.println("E");
}
outs.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
DataInputStream in = new DataInputStream(is);
byte[] buff = new byte[1024];
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int len = -1;
while((len = in.read(buff)) != -1){
buffer.write(buff, 0, len);
}
String msg = new String(buffer.toByteArray());
if(!"".equals(msg) && msg!=null){
return "A";
}else{
return "E";
}
public class ServerSocketTest {
public static void main(String[] args) {
try {
//服务器端
ServerSocket ss=new ServerSocket(10000);
Socket sck=ss.accept();
//获得输入输出流
InputStream is=sck.getInputStream();
OutputStream os=sck.getOutputStream();
String s=null;
int size=0;
byte[] temp=new byte[512];
while(true&&(size=is.read(temp))!=-1){
s=new String(temp,0,size);
System.out.println(s);
if("exit".equals(s)){
os.write(temp);
ss.close();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//客户端
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
try {
Socket sc = new Socket("127.171.0.101", 10000);
InputStream is = sc.getInputStream();
OutputStream oos = sc.getOutputStream();
byte[] b = new byte[512];
Scanner scc = new Scanner(System.in);
while (true) {
String s = scc.nextLine();
oos.flush();
oos.write(s.getBytes());
if ("exit".equals(s)) {
sc.close();
break;
}
}
// byte[] temp=new byte[512];
// is.read(temp);
// if(){
// sc.close();
// }
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}