UIPethernet TCP persistent server with two way communication

Hi Guys,

I am very new to Arduino, so please be patient. I was trying to run TCP server using UIPethernet library on Arduino Mega 2560 +Enc28J60. The problem I am having is after few hours or sometimes few minutes the server stopped working and the client complain about the socket connection.

So I tried the example given with the UIPEthernet library.

#include <SPI.h>
#include <UIPEthernet.h>

EthernetServer server = EthernetServer(1000);

void setup()

  uint8_t mac[6] = {0x00,0x01,0x02,0x03,0x04,0x05};
  IPAddress myIP(172,16,12,149);



void loop()
  size_t size;

  if (EthernetClient client = server.available())
      while((size = client.available()) > 0)
          uint8_t* msg = (uint8_t*)malloc(size);
          size = client.read(msg,size);
      client.println("DATA from Server!");

the only addition I did was " client.write(msg,size); " to make it kind of echo server. I used my python script to connect to server.

import select
import socket
import time
import sys

def make_connection(ip=''):
    TCP_IP = ip
    TCP_PORT = 1000
    BUFFER_SIZE = 1024
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((TCP_IP, TCP_PORT))        
        sys.stdout.write("error: socket connection failed")
        return False,False

    return True,s

state,s = make_connection()
while (1):
        state,s = make_connection()
        s.send("Remember My name!! walter\n")
        lines = s.recv(4096)
        print " Walter W... died"
    print lines

The script is making connection every 0.2 sec approx and sending a sentence and reading the same sentence back. What happen is after some time, the python script complain about the socket connection or it receive nothing back. If I try to connect it again, the socket connection won’t connect. hence I need to power-cycle the Arduino in order to get it running. I have been playing around with different options but nothing working for me. I also tried the echoserver example with no success. The interesting thing is when I don’t echo anything back from the TCP_server, It seems to work for ages. I hope I am clear in explaining my problem. thanks

I have added "client.flush()" on the server side before closing the connection using client.stop(). Things are looking little better. The server has been running for 1-hour and counting....

so its has been working since...