50,530
社区成员
发帖
与我相关
我的任务
分享
public class Client implements Runnable {
Socket socket;
public static void main(String[] arg) throws UnknownHostException{
Thread t = new Thread(new Client(InetAddress.getLocalHost(), 5000));
t.start();
}
public Client(InetAddress addr, int port){
try{
socket = new Socket(addr, 5000);
}catch(Exception e){
e.printStackTrace(System.err);
}
}
@Override
public void run() {
// TODO Auto-generated method stub
Scanner s = new Scanner(System.in);
try{
OutputStream os = socket.getOutputStream();
String temp = null;
while((temp = s.next()) != null){
os.write(temp.getBytes());
if("e".equals(temp)){
break;
}
}
os.close();
socket.close();
}catch(Exception e){
e.printStackTrace(System.err);
}
}
}
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(5000);
while (true) {
MuiThread server = new MuiThread(ss.accept());
new Thread(server).start();
}
}
}
class MuiThread implements Runnable {
Socket socket;
MuiThread(Socket socket) {
this.socket = socket;
}
public void run() {
try {
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
os.write("Welcome".getBytes());
while (true) {
byte[] b = new byte[100];
int len = is.read(b);
String str = new String(b, 0, len);
if (str.equals("e")) {
os.write("the Server will close at once".getBytes());
System.out.println("Client is Disconnectiong");
break;
} else {
System.out.println(str);
}
}
is.close();
os.close();
socket.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
import java.net.*;
import java.io.*;
class Server {
public static void main(String[] args) throws IOException {
ServerSocket ss = new ServerSocket(5000);
while (true) {
Socket s = ss.accept();
MuiThread mt = new MuiThread(s);
new Thread(mt).start();
}
}
}
class MuiThread implements Runnable {
Socket s;
InputStream is;
OutputStream os;
String str;
MuiThread(Socket s) {
this.s = s;
is = null;
os = null;
str = null;
}
public void run() {
try {
is = s.getInputStream();
os = s.getOutputStream();
os.write("Welcome".getBytes());
byte[] b = new byte[100];
int len = is.read(b);
str = new String(b, 0, len);
if (str.equals("e")) {
os.write("the Server will close at once".getBytes());
System.out.println("Client is Disconnectiong");
} else {
System.out.println(str);
}
} catch (Exception e) {
System.out.println(e);
}
}
}