手写TCP客户端和服务端

JAVA ZMAS 75℃ 0评论

//客户端
package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {
public static void main(String[] args) {
System.out.println(“客户端就绪 over “);
Scanner scanner=new Scanner(System.in);
Socket socket=null;
OutputStream os=null;
InputStream is=null;
ServerSocket serverSocket=null;
try {
while (true) {
socket=new Socket(“127.0.0.1”, 2019);
String string=scanner.next();
if(string.equals(“byebye”)){
break;
}
os=socket.getOutputStream();
os.write(string.getBytes());
os.flush();

//不需要再建立连接
is=socket.getInputStream();
byte[] bs=new byte[30];
int num=is.read(bs);
String string1=new String(bs,0,num);
System.out.println(string1);
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(os!=null){
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
//服务端
package server;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class Server {
public static void main(String[] args) {
System.out.println(“服务器就绪 over!”);
ServerSocket serverSocket=null;
Socket socket=null;
InputStream is=null;
OutputStream os=null;
Scanner scanner=new Scanner(System.in);
try {
serverSocket=new ServerSocket(2019);
while(true){
socket=serverSocket.accept();
is=socket.getInputStream();
byte[] bs=new byte[30];
int num=is.read(bs);
String string=new String(bs,0,num);
System.out.println(string);
String string1=scanner.next();
if(string1.equals(“byebye”)){
break;
}
//socket=new Socket(socket.getInetAddress(), socket.getPort());
//不需要再建立连接
os=socket.getOutputStream();
os.write(string1.getBytes());
os.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(is!=null){
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}

转载请注明:ZMAS‘S blog » 手写TCP客户端和服务端

喜欢 (4)
发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址