按你的要求,小弟做了这个程序,发送两次,均送到。试一试把
import java.io.*;
import java.net.*;public class TestTCP{
public static void main(String args[]){
Server s = new Server(8000);
try{
Thread.sleep(100);
}catch(Exception e){
e.printStackTrace();
}
Client c = new Client("localhost",8000);
c.send("Hello");
c.send("World!");
s.print();
}
}
class Server implements Runnable{
private ServerSocket server;
private Socket client;
public Server(int port){
try{
System.out.println("constructing server...");
server = new ServerSocket(port);
Thread t = new Thread(this);
t.start();
}catch(Exception e){
e.printStackTrace();
}
}
public void print(){
try{
BufferedReader br = new BufferedReader
(new InputStreamReader(client.getInputStream()));
String str;
str = br.readLine();
while(str!=null){
System.out.println("server get msg:\""+str+"\"");
str = br.readLine();
}
}catch(Exception e){
e.printStackTrace();
}
}
public void run(){
try{
System.out.println("listening for client...");
client = server.accept();
}catch(Exception e){
e.printStackTrace();
}
}
}
class Client{
private Socket client;
public Client(String host,int port){
try{
System.out.println("Constructing client...");
client = new Socket(host,port);
}catch(Exception e){
e.printStackTrace();
}
}
public void send(String str){
try{
OutputStreamWriter osw = new OutputStreamWriter
(client.getOutputStream());
System.out.println("Client sending msg:\""+str+"\"");
osw.write(str+"\n");
osw.flush();
}catch(Exception e){
e.printStackTrace();
}
}
}
import java.io.*;
import java.net.*;public class TestTCP{
public static void main(String args[]){
Server s = new Server(8000);
try{
Thread.sleep(100);
}catch(Exception e){
e.printStackTrace();
}
Client c = new Client("localhost",8000);
c.send("Hello");
c.send("World!");
s.print();
}
}
class Server implements Runnable{
private ServerSocket server;
private Socket client;
public Server(int port){
try{
System.out.println("constructing server...");
server = new ServerSocket(port);
Thread t = new Thread(this);
t.start();
}catch(Exception e){
e.printStackTrace();
}
}
public void print(){
try{
BufferedReader br = new BufferedReader
(new InputStreamReader(client.getInputStream()));
String str;
str = br.readLine();
while(str!=null){
System.out.println("server get msg:\""+str+"\"");
str = br.readLine();
}
}catch(Exception e){
e.printStackTrace();
}
}
public void run(){
try{
System.out.println("listening for client...");
client = server.accept();
}catch(Exception e){
e.printStackTrace();
}
}
}
class Client{
private Socket client;
public Client(String host,int port){
try{
System.out.println("Constructing client...");
client = new Socket(host,port);
}catch(Exception e){
e.printStackTrace();
}
}
public void send(String str){
try{
OutputStreamWriter osw = new OutputStreamWriter
(client.getOutputStream());
System.out.println("Client sending msg:\""+str+"\"");
osw.write(str+"\n");
osw.flush();
}catch(Exception e){
e.printStackTrace();
}
}
}
1。送完数据,flush流
2。直接用println就可以了。